深度学习系列之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课程作业红色石头版

发布了27 篇原创文章 · 获赞 124 · 访问量 4933

猜你喜欢

转载自blog.csdn.net/qq_35149632/article/details/104851273