深度學習系列之cs231n assignment1 svm(三)

寫在開頭:終於又copy完了大佬的svm的作業,該由我抄過來了,我在響應的位置會附上講得比較好的大佬的鏈接,感謝他們。
最近面臨找實習,這個就業壓力還是挺大,自己又這麼菜怎麼辦呢,還是得抽空抓好機器學習的功夫,然後再加點深度學習的框架和SQL以及Hadoop的學習應該就差不多了,所以在明年9月前,一定要把自己培養的至少能夠在實習生中立足的水平。後面重新理一下計劃,還有更新內容的形式。

內容安排

今天要分享的內容呢就是cs231n課程後面assignment1的關於線性svm的實現的作業的一個完整版分享,中途會用到的公式我會截圖分享出來,這次的使用文件仍然與上次一樣需要打開svm的ipynb後綴的文件,然後需要用到的py文件分別爲linear_classifier和linear_svm兩個文件,這次筆者就會按照官方文檔那樣排版了,保留官方英文註釋,並在筆者認爲重要的地方作出註釋,然後再我想斷句解釋的地方進行解釋,儘量把這個一個作業給講清楚。

開始完成作業

1.加載數據
首先我們需要加載數據,可以不用管內容直接進行加載,這兩步與上一節KNN相同,

# Run some setup code for this notebook.

import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt



# This is a bit of magic to make matplotlib figures appear inline in the
# notebook rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
# Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)

# As a sanity check, we print out the size of the training and test data.
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
Training data shape:  (50000, 32, 32, 3)
Training labels shape:  (50000,)
Test data shape:  (10000, 32, 32, 3)
Test labels shape:  (10000,)
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
num_classes = len(classes)
samples_per_class = 7
for y, cls in enumerate(classes):
    idxs = np.flatnonzero(y_train == y)
    idxs = np.random.choice(idxs, samples_per_class, replace=False)
    for i, idx in enumerate(idxs):
        plt_idx = i * num_classes + y + 1
        plt.subplot(samples_per_class, num_classes, plt_idx)
        plt.imshow(X_train[idx].astype('uint8'))
        plt.axis('off')
        if i == 0:
            plt.title(cls)
plt.show()

在這裏插入圖片描述
2.數據預處理
這裏我們需要將數據劃分爲train訓練集、val驗證集、test測試集以及dev試算集,這個試算集就是一個小樣本來測試程序是否能夠正常運行的。這裏在選取的測試集的時候我們是不能夠讓val測試集和train訓練集有交集的,這樣才能達到隨機的效果。

# Split the data into train, val, and test sets. In addition we will
# create a small development set as a subset of the training data;
# we can use this for development so our code runs faster.
num_training = 49000
num_validation = 1000
num_test = 1000
num_dev = 500

# Our validation set will be num_validation points from the original
# training set.
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]

# Our training set will be the first num_train points from the original
# training set.
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]

# We will also make a development set, which is a small subset of
# the training set.
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]

# We use the first num_test points of the original test set as our
# test set.
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]

print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
Train data shape:  (49000, 32, 32, 3)
Train labels shape:  (49000,)
Validation data shape:  (1000, 32, 32, 3)
Validation labels shape:  (1000,)
Test data shape:  (1000, 32, 32, 3)
Test labels shape:  (1000,)

下面需要對數據進行向量化處理,因爲我們的線性svm採用的是Wx的矩陣乘法,W每一列代表着某個類別的所有像素模板,X的每一行代表着每個樣本的所有像素點的向量化後的值,

# Preprocessing: reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_val = np.reshape(X_val, (X_val.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))

# As a sanity check, print out the shapes of the data
print('Training data shape: ', X_train.shape)
print('Validation data shape: ', X_val.shape)
print('Test data shape: ', X_test.shape)
print('dev data shape: ', X_dev.shape)
Training data shape:  (49000, 3072)
Validation data shape:  (1000, 3072)
Test data shape:  (1000, 3072)
dev data shape:  (500, 3072)

下面再來展示一下所以訓練樣本的像素點均值繪製出來的圖像是什麼樣子,

# Preprocessing: subtract the mean image
# first: compute the image mean based on the training data
mean_image = np.mean(X_train, axis=0)
print(mean_image[:10]) # print a few of the elements
plt.figure(figsize=(4,4))
plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image
plt.show()
[130.64189 135.98174 132.47392 130.0557  135.34804 131.75401 130.96056
 136.14328 132.47636 131.48468]

在這裏插入圖片描述
然後所有訓練測試樣本全部減去這樣一個像素均值,這一步的具體操作不是很懂,但是從統計學上經常減均值的操作事項移動中心點,我們放在這邊來理解的話,可能是爲了使得各維度的中心點位0,然後減小過擬合的程度,相當於是縮減了特徵值的程度,減小計算量,這裏參考該鏈接文章去均值、白化和中心化的區別

# second: subtract the mean image from train and test data
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
X_dev -= mean_image

最後再添加一項用於偏差的一項,

# third: append the bias dimension of ones (i.e. bias trick) so that our SVM
# only has to worry about optimizing a single weight matrix W.
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])
X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))])
X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])
X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))])

print(X_train.shape, X_val.shape, X_test.shape, X_dev.shape)
(49000, 3073) (1000, 3073) (1000, 3073) (500, 3073)

3.完成並運行SVM
這裏如果我們直接運行jupyter中的ipynb的svm代碼會輸出異常,因爲我們的svm核心代碼還沒有編寫,此時需要打開linear_svm.py的文件對ToDo任務進行程序的編寫,在此文件中我們共有兩個任務需要完成,第一個是利用循環來編寫求w的梯度的計算程序,第二個是利用向量矩陣運算計算loss損失函數以及w的梯度,並輸出。如果有朋友不瞭解梯度是什麼的,可以理解爲偏導數,所以我們知道一個最傳統的求導數的那就是利用導數的定義,但此方法需要對參數一個一個的進行更新,十分的緩慢,於是我們利用微積分,就可以得到梯度,此時我們假設全文使用這樣一個損失函數,
在這裏插入圖片描述
這裏的delta我們常取1,表示當正確類的預測得分函數要大於錯位類的預測得分函數+1,我們才承認預測時無損失的,這個函數表示的意思就是當我們的第i個樣本進行預測時,將i各樣本預測爲錯誤類與正確類的得分+1之和,也就是對於第i個樣本的損失。
那麼對這個函數求梯度只需要對對應的w求導就可以了,於是得到,
在這裏插入圖片描述
上式是對於錯誤分類後的梯度計算,1()是一個示性函數,如果滿足括號內條件返回1否則返回0,也就是是說對於預測錯誤類的梯度就等於對應x的像素值。然後對於預測正確的類的梯度就是,對於第i類預測的所有損失的加總的相反數,我們更新權重的時候要向反方向更新,直觀的理解就是當正確類別的偏度絕對值越大的時候,說明需要更加增強他的權重,因爲不增加權重就預測得太不準了。
在這裏插入圖片描述
於是這就是我們計算dW梯度的核心公式,其實也就是判斷得分標準是否大於0,如果大於0對錯誤類返回xi對正確類返回-xi,於是我們來展示一下此段的代碼完成,

import numpy as np
from random import shuffle
from past.builtins import xrange

def svm_loss_naive(W, X, y, reg):
  """
  Structured SVM loss function, naive implementation (with loops).

  Inputs have dimension D, there are C classes, and we operate on minibatches
  of N examples.

  Inputs:
  - W: A numpy array of shape (D, C) containing weights.
  - X: A numpy array of shape (N, D) containing a minibatch of data.
  - y: A numpy array of shape (N,) containing training labels; y[i] = c means
    that X[i] has label c, where 0 <= c < C.
  - reg: (float) regularization strength

  Returns a tuple of:
  - loss as single float
  - gradient with respect to weights W; an array of same shape as W
  """
  dW = np.zeros(W.shape) # initialize the gradient as zero

  # compute the loss and the gradient
  num_classes = W.shape[1]
  num_train = X.shape[0]
  loss = 0.0
  for i in xrange(num_train):
    scores = X[i].dot(W)
    correct_class_score = scores[y[i]]
    for j in xrange(num_classes):
      if j == y[i]:
        continue
      margin = scores[j] - correct_class_score + 1 # note delta = 1
      if margin > 0:
        loss += margin
        dW[:,j] += X[i].T
        dW[:,y[i]] -= X[i].T
  # Right now the loss is a sum over all training examples, but we want it
  # to be an average instead so we divide by num_train.
  loss /= num_train
  dW /= num_train
  # Add regularization to the loss.
  loss += reg * np.sum(W * W)
  dW += reg * W
  #############################################################################
  # TODO:                                                                     #
  # Compute the gradient of the loss function and store it dW.                #
  # Rather that first computing the loss and then computing the derivative,   #
  # it may be simpler to compute the derivative at the same time that the     #
  # loss is being computed. As a result you may need to modify some of the    #
  # code above to compute the gradient.                                       #
  #############################################################################


  return loss, dW


def svm_loss_vectorized(W, X, y, reg):
  """
  Structured SVM loss function, vectorized implementation.

  Inputs and outputs are the same as svm_loss_naive.
  """
  loss = 0.0
  dW = np.zeros(W.shape) # initialize the gradient as zero

  #############################################################################
  # TODO:                                                                     #
  # Implement a vectorized version of the structured SVM loss, storing the    #
  # result in loss.                                                           #
  #############################################################################
  pass
  num_train = X.shape[0]
  scores = np.dot(X, W)
  correct_class_score = scores[range(num_train), list(y)].reshape(-1, 1)#變成列
  margin = np.maximum(0, scores - correct_class_score + 1)
  margin[range(num_train), list(y)] = 0
  loss = np.sum(margin)/num_train + reg * np.sum(W*W)
  #############################################################################
  #                             END OF YOUR CODE                              #
  #############################################################################


  #############################################################################
  # TODO:                                                                     #
  # Implement a vectorized version of the gradient for the structured SVM     #
  # loss, storing the result in dW.                                           #
  #                                                                           #
  # Hint: Instead of computing the gradient from scratch, it may be easier    #
  # to reuse some of the intermediate values that you used to compute the     #
  # loss.                                                                     #
  #############################################################################
  pass
  num_class = W.shape[1]
  m = np.zeros((num_train, num_class))
  m[margin > 0] = 1
  m[range(num_train), list(y)] = 0
  m[range(num_train), list(y)] = -np.sum(m, axis=1)
  dW = np.dot(X.T, m)/num_train + reg * W

  #############################################################################
  #                             END OF YOUR CODE                              #
  #############################################################################

  return loss, dW

代碼完成了在此文章中所需要做的3個任務,值得一提的是,我們需要對計算出來的dw和loss都加上一個reg正則項來避免其過擬合。
於是我們來運行作業代碼,看看計算的結果,

# Evaluate the naive implementation of the loss we provided for you:
from cs231n.classifiers.linear_svm import svm_loss_naive
import time

# generate a random SVM weight matrix of small numbers
W = np.random.randn(3073, 10) * 0.0001 

loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.000005)
print('loss: %f' % (loss, ))

首先得出svm的常規循環計算得到的損失函數,這一步不需要我們編寫內容,

loss: 9.035526

然後運行接下來的代碼,會測試我們寫的損失函數是否正確,一個判斷標準就是將我們用微積分得到的解與導數定義得到的解進行對比,如果差異不大,說明計算正確,

# Once you've implemented the gradient, recompute it with the code below
# and gradient check it with the function we provided for you
from cs231n.classifiers.linear_svm import svm_loss_naive
import time
# Compute the loss and its gradient at W.
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.0)

# Numerically compute the gradient along several randomly chosen dimensions, and
# compare them with your analytically computed gradient. The numbers should match
# almost exactly along all dimensions.
from cs231n.gradient_check import grad_check_sparse
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 0.0)[0]
grad_numerical = grad_check_sparse(f, W, grad)

# do the gradient check once again with regularization turned on
# you didn't forget the regularization gradient did you?
loss, grad = svm_loss_naive(W, X_dev, y_dev, 5e1)
f = lambda w: svm_loss_naive(w, X_dev, y_dev, 5e1)[0]
grad_numerical = grad_check_sparse(f, W, grad)
numerical: -11.134769 analytic: -11.134769, relative error: 7.492919e-12
numerical: -26.201969 analytic: -26.201969, relative error: 2.276806e-11
numerical: 17.007888 analytic: 17.007888, relative error: 8.322863e-12
numerical: 24.357402 analytic: 24.357402, relative error: 3.966234e-12
numerical: 11.060589 analytic: 11.060589, relative error: 1.475823e-11
numerical: 14.618717 analytic: 14.618717, relative error: 6.643635e-12
numerical: -28.965377 analytic: -28.965377, relative error: 1.620809e-12
numerical: -12.924270 analytic: -12.924270, relative error: 1.946887e-12
numerical: -37.095280 analytic: -37.095280, relative error: 3.942003e-12
numerical: 16.260672 analytic: 16.260672, relative error: 4.586001e-13
numerical: -35.859216 analytic: -35.862116, relative error: 4.042911e-05
numerical: -0.298664 analytic: -0.288489, relative error: 1.732885e-02
numerical: 20.924849 analytic: 20.921766, relative error: 7.368654e-05
numerical: 15.027211 analytic: 15.025921, relative error: 4.291960e-05
numerical: 6.215818 analytic: 6.223036, relative error: 5.802678e-04
numerical: 0.161299 analytic: 0.156143, relative error: 1.624406e-02
numerical: -9.542728 analytic: -9.541662, relative error: 5.582052e-05
numerical: 3.184572 analytic: 3.178109, relative error: 1.015709e-03
numerical: 7.230887 analytic: 7.239002, relative error: 5.608088e-04
numerical: 37.075271 analytic: 37.067189, relative error: 1.090062e-04

我們可以看到numericla和analytic計算的loss十分接近,所以認爲編程沒有問題,但又有一個問題出來了,爲什麼兩者計算的結果還是會有微小的差異,這個問題我們留在後續系列的思考題中進行分析。
下面需要用到剛剛編寫的矩陣運算求loss和dw的函數,其實矩陣運算的思路就是一個整體操作,將for循環進行整體呈整體操作,只是具體實現細節可能需要編程注意,

# Next implement the function svm_loss_vectorized; for now only compute the loss;
# we will implement the gradient in a moment.
tic = time.time()
loss_naive, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Naive loss: %e computed in %fs' % (loss_naive, toc - tic))
print(loss)
Naive loss: 9.138494e+00 computed in 0.092990s
9.15405317783763
from cs231n.classifiers.linear_svm import svm_loss_vectorized
tic = time.time()
loss_vectorized, _ = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()
print('Vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic))
print(loss_vectorized)
# The losses should match but your vectorized implementation should be much faster.
print(loss_naive - loss_vectorized)
Vectorized loss: 9.138494e+00 computed in 0.001954s
9.138493682409688
2.4868995751603507e-14

可以看到向量計算的結果與for循環結果差異很小,具體可能是儲存精度不一樣導致的。當然我們對於loss還是比較好比較的因爲就一個數值,爲了比較兩種方法計算的梯度是否有差異我們使用F範數進行分析,

# Complete the implementation of svm_loss_vectorized, and compute the gradient
# of the loss function in a vectorized way.

# The naive implementation and the vectorized implementation should match, but
# the vectorized version should still be much faster.
tic = time.time()
_, grad_naive = svm_loss_naive(W, X_dev, y_dev, 0.000005)
toc = time.time()

print('Naive loss and gradient: computed in %fs' % (toc - tic))

tic = time.time()
_, grad_vectorized = svm_loss_vectorized(W, X_dev, y_dev, 0.000005)
toc = time.time()

print('Vectorized loss and gradient: computed in %fs' % (toc - tic))

# The loss is a single number, so it is easy to compare the values computed
# by the two implementations. The gradient on the other hand is a matrix, so
# we use the Frobenius norm to compare them.
difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro')
print('difference: %f' % difference)
Vectorized loss and gradient: computed in 0.015625s
difference: 0.000000

可以看到也是幾乎無差異,而且向量運算計算的速度更快。當然即使運算速度再快,當我們面對大量數據的時候,如果每次都去運算所有的數據,或者書通過所有數據來更新權重的話,無疑會很大的增加計算的負擔,爲了解決這個問題,我們使用SGD也就是隨機梯度下降,這個方法與梯度下降的區別就在隨機上,主要思路就是對5000行數據隨機去200個這種思想,(使用numpy.random.choice可以實現這個想法)然後利用局部數據進行迭代,然後選取2000次這樣就能夠快速的進行計算,用小規模數據更新權重,那麼接下來就涉及到了另一個文件linear_classifier.py中的train函數,裏面填充的是隨機梯度下降的核心函數,而我們需要做的就是實現隨機收取數據。然後裏面還有一個需要完成的是根據最後得到的W來預測我們的train數據的類別。具體代碼如下,

from __future__ import print_function

import numpy as np
from cs231n.classifiers.linear_svm import *
from cs231n.classifiers.softmax import *
from past.builtins import xrange


class LinearClassifier(object):

  def __init__(self):
    self.W = None

  def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100,
            batch_size=200, verbose=False):
    """
    Train this linear classifier using stochastic gradient descent.

    Inputs:
    - X: A numpy array of shape (N, D) containing training data; there are N
      training samples each of dimension D.
    - y: A numpy array of shape (N,) containing training labels; y[i] = c
      means that X[i] has label 0 <= c < C for C classes.
    - learning_rate: (float) learning rate for optimization.
    - reg: (float) regularization strength.
    - num_iters: (integer) number of steps to take when optimizing
    - batch_size: (integer) number of training examples to use at each step.
    - verbose: (boolean) If true, print progress during optimization.

    Outputs:
    A list containing the value of the loss function at each training iteration.
    """
    num_train, dim = X.shape
    num_classes = np.max(y) + 1 # assume y takes values 0...K-1 where K is number of classes
    if self.W is None:
      # lazily initialize W
      self.W = 0.001 * np.random.randn(dim, num_classes)

    # Run stochastic gradient descent to optimize W
    loss_history = []
    for it in xrange(num_iters):
      index = np.random.choice(num_train, batch_size, replace=True)
      X_batch = X[index]
      y_batch = y[index]

      #########################################################################
      # TODO:                                                                 #
      # Sample batch_size elements from the training data and their           #
      # corresponding labels to use in this round of gradient descent.        #
      # Store the data in X_batch and their corresponding labels in           #
      # y_batch; after sampling X_batch should have shape (dim, batch_size)   #
      # and y_batch should have shape (batch_size,)                           #
      #                                                                       #
      # Hint: Use np.random.choice to generate indices. Sampling with         #
      # replacement is faster than sampling without replacement.              #
      #########################################################################
      pass
      #########################################################################
      #                       END OF YOUR CODE                                #
      #########################################################################

      # evaluate loss and gradient
      loss, grad = self.loss(X_batch, y_batch, reg)
      loss_history.append(loss)
      self.W += -learning_rate * grad
      # perform parameter update
      #########################################################################
      # TODO:                                                                 #
      # Update the weights using the gradient and the learning rate.          #
      #########################################################################
      pass
      #########################################################################
      #                       END OF YOUR CODE                                #
      #########################################################################

      if verbose and it % 100 == 0:
        print('iteration %d / %d: loss %f' % (it, num_iters, loss))

    return loss_history

  def predict(self, X):
    """
    Use the trained weights of this linear classifier to predict labels for
    data points.

    Inputs:
    - X: A numpy array of shape (N, D) containing training data; there are N
      training samples each of dimension D.

    Returns:
    - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional
      array of length N, and each element is an integer giving the predicted
      class.
    """
    y_pred = np.zeros(X.shape[0])
    scores = np.dot(X, self.W)
    y_pred = np.argmax(scores, axis=1)
    ###########################################################################
    # TODO:                                                                   #
    # Implement this method. Store the predicted labels in y_pred.            #
    ###########################################################################
    pass
    ###########################################################################
    #                           END OF YOUR CODE                              #
    ###########################################################################
    return y_pred
  
  def loss(self, X_batch, y_batch, reg):
    """
    Compute the loss function and its derivative. 
    Subclasses will override this.

    Inputs:
    - X_batch: A numpy array of shape (N, D) containing a minibatch of N
      data points; each point has dimension D.
    - y_batch: A numpy array of shape (N,) containing labels for the minibatch.
    - reg: (float) regularization strength.

    Returns: A tuple containing:
    - loss as a single float
    - gradient with respect to self.W; an array of the same shape as W
    """
    pass


class LinearSVM(LinearClassifier):
  """ A subclass that uses the Multiclass SVM loss function """

  def loss(self, X_batch, y_batch, reg):
    return svm_loss_vectorized(self.W, X_batch, y_batch, reg)


class Softmax(LinearClassifier):
  """ A subclass that uses the Softmax + Cross-entropy loss function """

  def loss(self, X_batch, y_batch, reg):
    return softmax_loss_vectorized(self.W, X_batch, y_batch, reg)

那麼我們來運行一下作業代碼,看看運行結果吧,

# In the file linear_classifier.py, implement SGD in the function
# LinearClassifier.train() and then run it with the code below.

from cs231n.classifiers import LinearSVM
svm = LinearSVM()
tic = time.time()
loss_hist = svm.train(X_train, y_train, learning_rate=1e-7, reg=2.5e4,
                      num_iters=2000, verbose=True)
toc = time.time()
print('That took %fs' % (toc - tic))
iteration 0 / 2000: loss 785.193662
iteration 100 / 2000: loss 469.951361
iteration 200 / 2000: loss 285.152670
iteration 300 / 2000: loss 173.940086
iteration 400 / 2000: loss 106.734203
iteration 500 / 2000: loss 66.067783
iteration 600 / 2000: loss 41.010264
iteration 700 / 2000: loss 27.581060
iteration 800 / 2000: loss 18.393378
iteration 900 / 2000: loss 12.956286
iteration 1000 / 2000: loss 10.400926
iteration 1100 / 2000: loss 8.312311
iteration 1200 / 2000: loss 6.956938
iteration 1300 / 2000: loss 6.775997
iteration 1400 / 2000: loss 5.950798
iteration 1500 / 2000: loss 5.256139
iteration 1600 / 2000: loss 5.524237
iteration 1700 / 2000: loss 5.749462
iteration 1800 / 2000: loss 6.222899
iteration 1900 / 2000: loss 5.239182
That took 9.655279s

可以看到隨着迭代次數的不斷增加,總體的損失函數是不斷減小的,也就是說預測精度是在不斷增加的。下面繪圖來感受一下,

# A useful debugging strategy is to plot the loss as a function of
# iteration number:
plt.plot(loss_hist)
plt.xlabel('Iteration number')
plt.ylabel('Loss value')
plt.show()

在這裏插入圖片描述
所以可以看到隨着迭代次數的增加損失函數大小快速的減小並趨於平穩,下面來看看對train和val數據預測的精度吧,

# Write the LinearSVM.predict function and evaluate the performance on both the
# training and validation set
y_train_pred = svm.predict(X_train)
print('training accuracy: %f' % (np.mean(y_train == y_train_pred), ))
y_val_pred = svm.predict(X_val)
print('validation accuracy: %f' % (np.mean(y_val == y_val_pred), ))
training accuracy: 0.376714
validation accuracy: 0.388000

精度在0.37和0.38總體不算好,但對於線性svm來說結果還可以。最後使用交叉驗證,來選擇出最好的參數,這裏我們是通過不同參數訓練train數據,然後對val數據進行驗證,選擇出最準確的那一組參數代入test進行最後結果的輸出。
這裏還有最後一個任務,就是完成交叉驗證的代碼,其主要思想呢就是循環不同的參數進行預測,然後不斷更新保留最準確的參數。具體代碼如下,

# Use the validation set to tune hyperparameters (regularization strength and
# learning rate). You should experiment with different ranges for the learning
# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of about 0.4 on the validation set.

learning_rates = [1.4e-7, 1.5e-7, 1.6e-7]
regularization_strengths = [8000.0, 9000.0, 10000.0, 11000.0, 18000.0, 19000.0, 20000.0, 21000.0]

# results is dictionary mapping tuples of the form
# (learning_rate, regularization_strength) to tuples of the form
# (training_accuracy, validation_accuracy). The accuracy is simply the fraction
# of data points that are correctly classified.
results = {}
best_lr = None
best_reg = None
best_val = -1   # The highest validation accuracy that we have seen so far.
best_svm = None # The LinearSVM object that achieved the highest validation rate.
for lr in learning_rates:
    for reg in regularization_strengths:
        svm = LinearSVM()
        loss_history = svm.train(X_train, y_train, learning_rate = lr, reg = reg, num_iters = 5000)
        y_train_pred = svm.predict(X_train)
        accuracy_train = np.mean(y_train_pred == y_train)
        y_val_pred = svm.predict(X_val)
        accuracy_val = np.mean(y_val_pred == y_val)
        if accuracy_val > best_val:
            best_lr = lr
            best_reg = reg
            best_val = accuracy_val
            best_svm = svm
        results[(lr, reg)] = accuracy_train, accuracy_val
        
################################################################################
# TODO:                                                                        #
# Write code that chooses the best hyperparameters by tuning on the validation #
# set. For each combination of hyperparameters, train a linear SVM on the      #
# training set, compute its accuracy on the training and validation sets, and  #
# store these numbers in the results dictionary. In addition, store the best   #
# validation accuracy in best_val and the LinearSVM object that achieves this  #
# accuracy in best_svm.                                                        #
#                                                                              #
# Hint: You should use a small value for num_iters as you develop your         #
# validation code so that the SVMs don't take much time to train; once you are #
# confident that your validation code works, you should rerun the validation   #
# code with a larger value for num_iters.                                      #
################################################################################
pass
################################################################################
#                              END OF YOUR CODE                                #
################################################################################
    
# Print out results.
for lr, reg in sorted(results):
    train_accuracy, val_accuracy = results[(lr, reg)]
    print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
                lr, reg, train_accuracy, val_accuracy))
    
print('best validation accuracy achieved during cross-validation: %f' % best_val)
lr 1.400000e-07 reg 8.000000e+03 train accuracy: 0.399837 val accuracy: 0.402000
lr 1.400000e-07 reg 9.000000e+03 train accuracy: 0.391000 val accuracy: 0.396000
lr 1.400000e-07 reg 1.000000e+04 train accuracy: 0.392224 val accuracy: 0.393000
lr 1.400000e-07 reg 1.100000e+04 train accuracy: 0.391837 val accuracy: 0.392000
lr 1.400000e-07 reg 1.800000e+04 train accuracy: 0.383347 val accuracy: 0.393000
lr 1.400000e-07 reg 1.900000e+04 train accuracy: 0.377673 val accuracy: 0.373000
lr 1.400000e-07 reg 2.000000e+04 train accuracy: 0.383551 val accuracy: 0.386000
lr 1.400000e-07 reg 2.100000e+04 train accuracy: 0.383347 val accuracy: 0.385000
lr 1.500000e-07 reg 8.000000e+03 train accuracy: 0.394367 val accuracy: 0.390000
lr 1.500000e-07 reg 9.000000e+03 train accuracy: 0.392653 val accuracy: 0.393000
lr 1.500000e-07 reg 1.000000e+04 train accuracy: 0.393878 val accuracy: 0.402000
lr 1.500000e-07 reg 1.100000e+04 train accuracy: 0.385612 val accuracy: 0.365000
lr 1.500000e-07 reg 1.800000e+04 train accuracy: 0.382837 val accuracy: 0.393000
lr 1.500000e-07 reg 1.900000e+04 train accuracy: 0.377633 val accuracy: 0.386000
lr 1.500000e-07 reg 2.000000e+04 train accuracy: 0.383571 val accuracy: 0.383000
lr 1.500000e-07 reg 2.100000e+04 train accuracy: 0.384469 val accuracy: 0.382000
lr 1.600000e-07 reg 8.000000e+03 train accuracy: 0.393816 val accuracy: 0.390000
lr 1.600000e-07 reg 9.000000e+03 train accuracy: 0.394673 val accuracy: 0.394000
lr 1.600000e-07 reg 1.000000e+04 train accuracy: 0.392776 val accuracy: 0.392000
lr 1.600000e-07 reg 1.100000e+04 train accuracy: 0.387388 val accuracy: 0.383000
lr 1.600000e-07 reg 1.800000e+04 train accuracy: 0.383143 val accuracy: 0.393000
lr 1.600000e-07 reg 1.900000e+04 train accuracy: 0.381224 val accuracy: 0.390000
lr 1.600000e-07 reg 2.000000e+04 train accuracy: 0.379959 val accuracy: 0.387000
lr 1.600000e-07 reg 2.100000e+04 train accuracy: 0.375388 val accuracy: 0.397000
best validation accuracy achieved during cross-validation: 0.402000
# Visualize the cross-validation results
import math
x_scatter = [math.log10(x[0]) for x in results]
y_scatter = [math.log10(x[1]) for x in results]

# plot training accuracy
marker_size = 100
colors = [results[x][0] for x in results]
plt.subplot(2, 1, 1)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 training accuracy')

# plot validation accuracy
colors = [results[x][1] for x in results] # default size of markers is 20
plt.subplot(2, 1, 2)
plt.scatter(x_scatter, y_scatter, marker_size, c=colors)
plt.colorbar()
plt.xlabel('log learning rate')
plt.ylabel('log regularization strength')
plt.title('CIFAR-10 validation accuracy')
plt.show()

在這裏插入圖片描述
展示出了再不同參數下的預測精度的波動,下面對test利用最優參數進行預測來看一下預測精確度情況吧,

# Evaluate the best svm on test set
y_test_pred = best_svm.predict(X_test)
test_accuracy = np.mean(y_test == y_test_pred)
print('linear SVM on raw pixels final test set accuracy: %f' % test_accuracy)
linear SVM on raw pixels final test set accuracy: 0.377000

預測精度在0.37,這個結果與訓練集是差不多的說明沒有出現過擬合的情況,至於有沒有預測的更加精確,我們從之前損失函數那張圖可以看到,我們後面需要增加大量的迭代次數纔會對精度進行少量的提高,因此是不划算的,所以我們認爲這個預測結果還合理。
最後我們將我們訓練得到的W進行可視化展示,看看我們訓練半天到底訓練出來了個什麼東西,對於W的說明課程中說過是對於每個類別的一個模板,當樣本輸入後與模板相乘得到對應的得分,得分高的說明你對這個模板的各部分都很貼合,

# Visualize the learned weights for each class.
# Depending on your choice of learning rate and regularization strength, these may
# or may not be nice to look at.
w = best_svm.W[:-1,:] # strip out the bias
w = w.reshape(32, 32, 3, 10)
w_min, w_max = np.min(w), np.max(w)
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for i in range(10):
    plt.subplot(2, 5, i + 1)
      
    # Rescale the weights to be between 0 and 255
    wimg = 255.0 * (w[:, :, :, i].squeeze() - w_min) / (w_max - w_min)
    plt.imshow(wimg.astype('uint8'))
    plt.axis('off')
    plt.title(classes[i])

在這裏插入圖片描述
這個圖能隱約看出來horse就是上課說的雙頭馬了哈哈。


結語
那麼本次對於線性svm的分類實現有了一個初步的瞭解,後面會繼續更新這個系列。
謝謝閱讀。
參考
cs231n svm課程作業紅色石頭版

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章