CS231n作业+代码实践:Assignment1 SVM

Multiclass Support Vector Machine exercise

# Run some setup code for this notebook.

from __future__ import print_function
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

首先,这里还是跟上一个作业一样,要注意from __future__ import print_function要放到最上面(我也不知道为什么,看提示改的)

# Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'

# Cleaning up variables to prevent loading data multiple times (which may cause memory issue)
try:
   del X_train, y_train
   del X_test, y_test
   print('Clear previously loaded data.')
except:
   pass

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,)
# Visualize some examples from the dataset.
# We show a few examples of training images from each class.
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()

在这里插入图片描述
这上面的代码都和之前一模一样,所以不多赘述。
下面开始把样本分成三类,1.训练集 2.验证集3.测试集

# 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) #range生成val索引序列
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)#range生成train的索引序列
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) #随机从train挑选500个dev
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) #生成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,)

同理,我们还是把他们后面几个维度flatten,常用 np.reshape(X_train, (X_train.shape[0], -1))来把后面的维度合并(记下来)

# 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)

下面是一步预处理步骤,我们计算每个像素点在49000副图像里的均值。

mean_image = np.mean(X_train, axis=0)
print(mean_image[:10]) # 打印前10个像素点的平均值
plt.figure(figsize=(4,4)) #图像大小
plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image
plt.show()
(3072,)
[130.64189796 135.98173469 132.47391837 130.05569388 135.34804082
 131.75402041 130.96055102 136.14328571 132.47636735 131.48467347]

在这里插入图片描述
所有图像要减去均值图像的值,并且为了不引入b偏置项,我们把样本hstack一列全1项,这样就相当于有个b了。

# 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)

SVM分类器

本节的代码将全部写在cs231n / classifiers / linear_svm.py中。
如您所见,我们已经预填充了函数compute_loss_naive,该函数使用for循环来评估多类SVM损失函数。

# 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, ))

打开.py文件,找到简单svm算法,发现他已经写出来了loss的算法(这里用的是线性分类和svmloss去构建模型,下面这部分反向传播求梯度有些复杂,需要耐心一点计算)
这边我们要先计算一下导数dW:(为了与编程一致,我这边写成 y = x w y=xw y=xw(按照代码里的正向传播来写)的形式:
L i = 1 N ∑ j ≠ y i m a x ( 0 , s j − s y i + Δ ) + 1 2 λ ∥ w ∥ 2 L_{i} =\frac{1}{N}\sum_{j\neq y_i}max(0,s_j-s_{y_i}+\Delta)+\frac{1}{2}\lambda\Vert w\Vert^{2} Li=N1j=yimax(0,sjsyi+Δ)+21λw2

Δ \Delta Δ为选定的某个阈值。

L i = 1 N ∑ j ≠ y i m a x ( 0 , x i w j − x i w y i + Δ ) + 1 2 λ ∥ w ∥ 2 L_{i} =\frac{1}{N}\sum_{j\neq y_i}max(0,x_iw_j-x_iw_{y_{i}}+\Delta)+\frac{1}{2}\lambda\Vert w\Vert^{2} Li=N1j=yimax(0,xiwjxiwyi+Δ)+21λw2
于是W的每一列可以表示为:
[ S 00 S 01 . . . S 0 C S 10 S 11 . . . S 1 C . . . . . . . . . . . . S N 0 S N 1 . . . S N 1 ] = [ . . . X 0 . . . . . . X 1 . . . . . . . . . . . . . . . X N . . . ] [ ⋮ ⋮ ⋮ W 0 W 1 . . . W c ⋮ ⋮ ⋮ ] \begin{bmatrix} S_{00} &S_{01}&...&S_{0C} \\ S_{10} &S_{11}&...&S_{1C}\\ ...&...&...&...\\ S_{N0} &S_{N1}&...&S_{N1} \end{bmatrix} = \begin{bmatrix} ...&X_0&...\\...&X_1&...\\...&...&...\\...&X_N&...\end{bmatrix}\begin{bmatrix} \vdots&\vdots&&\vdots\\W_0&W_1&...&W_c\\\vdots&\vdots&&\vdots\end{bmatrix}\quad S00S10...SN0S01S11...SN1............S0CS1C...SN1=............X0X1...XN............W0W1...Wc

在每一张训练集i的图片循环(第一层循环
L i = ∑ j ≠ y i m a x ( 0 , x i w j − x i w y i + Δ ) L_i =\sum_{j\neq y_i}max(0,x_iw_j-x_iw_{y_{i}}+\Delta) Li=j=yimax(0,xiwjxiwyi+Δ)

又在j的循环(第二层循环),求导:

L i ∂ w j = { x i T x i w j − x i w y i > 0 0 x i w j − x i w y i ⩽ 0 \frac{L_i}{\partial w_j} =\left\{ \begin{aligned} x_i^T & &x_iw_j-x_iw_{y_{i}}>0 \\ 0 & &x_iw_j-x_iw_{y_{i}}\leqslant0 \\ \end{aligned} \right. wjLi={xiT0xiwjxiwyi>0xiwjxiwyi0

L i ∂ w y i = − x i T x i w j − x i w y i > 0 \frac{L_i}{\partial w_{yi}}=-x_i^T \quad x_iw_j-x_iw_{y_{i}}>0 wyiLi=xiTxiwjxiwyi>0
如果 x i w j − x i w y i + Δ > 0 x_iw_j-x_iw_{y_{i}}+\Delta>0 xiwjxiwyi+Δ>0,那么根据求导有:

d w j = d w j + x i T dw_j=dw_j+x_i^T dwj=dwj+xiT

d w y i = d w y i − x i T dw_{yi}=dw_{yi}-x_i^T dwyi=dwyixiT

最后还要加上 λ w \lambda w λw,因此:
d W = 1 N d W + λ w dW =\frac{1}{N} dW+\lambda w dW=N1dW+λw

这里的j代表W矩阵的每一列, x i x_i xi代表不同的训练样本

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]#10类
  num_train = X.shape[0] #num_train表示训练样本个数
  loss = 0.0
  for i in range(num_train):
    scores = X[i].dot(W)
    correct_class_score = scores[y[i]]
    for j in range(num_classes):
      if j == y[i]:   #j是真实样本
        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 += 0.5*reg * np.sum(W * W) #Np.sum(a*a)逐项相乘
  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

修改好上面之后,我们运行一下,检查一些输出grad的维度是不是与W的维度一样:

# 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, ))
print('gradient:\n',grad.shape)

进行梯度检查:

# Once you've implemented the gradient, recompute it with the code below
# and gradient check it with the function we provided for you

# 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: 23.085385 analytic: 23.085385, relative error: 1.172930e-11
numerical: -1.236521 analytic: -1.236521, relative error: 7.884760e-11
numerical: 6.910923 analytic: 6.845186, relative error: 4.778747e-03
numerical: -19.968839 analytic: -19.968839, relative error: 7.256444e-12
numerical: 11.331944 analytic: 11.331944, relative error: 2.770798e-11
numerical: -3.385788 analytic: -3.385788, relative error: 3.976704e-11
numerical: 20.107681 analytic: 20.107681, relative error: 7.589920e-12
numerical: 1.887162 analytic: 1.887162, relative error: 7.564024e-11
numerical: 21.488876 analytic: 21.417529, relative error: 1.662846e-03
numerical: -13.144394 analytic: -13.144394, relative error: 6.459439e-12
numerical: 30.272869 analytic: 30.272869, relative error: 5.525255e-12
numerical: 20.681273 analytic: 20.681273, relative error: 1.626950e-11
numerical: -3.407003 analytic: -3.374702, relative error: 4.762895e-03
numerical: 12.234011 analytic: 12.234011, relative error: 1.130557e-11
numerical: -2.756436 analytic: -2.756436, relative error: 9.104975e-11
numerical: 19.967492 analytic: 19.967492, relative error: 7.247770e-12
numerical: 32.355688 analytic: 32.355688, relative error: 2.117155e-11
numerical: 7.605475 analytic: 7.605475, relative error: 3.218538e-11
numerical: -3.685143 analytic: -3.685143, relative error: 2.872000e-11
numerical: 5.678984 analytic: 5.747740, relative error: 6.017125e-03

在前面的练习我们知道,用向量化的方法进行运算可以让程序快很多,所以接下来我们用向量化方法来计算loss和gradient:
这里我们还是要重点推到一下向量化的梯度 :(用矩阵来计算梯度,常用链式求导+维度分析)
∂ L ∂ W = ∂ L ∂ S ∂ S ∂ W = X T ∂ L ∂ S = X T [ . . . ∂ L ∂ S 1 . . . . . . ∂ L ∂ S 2 . . . . . . . . . . . . . . . ∂ L ∂ S N . . . ] \frac{\partial L}{\partial W} = \frac{\partial L}{\partial S} \frac{\partial S}{\partial W} = X^T\frac{\partial L}{\partial S}=X^T\begin{bmatrix} ...&\frac{\partial L}{\partial S_1}&...\\...&\frac{\partial L}{\partial S_2}&...\\...&...&...\\...&\frac{\partial L}{\partial S_N}&...\end{bmatrix} WL=SLWS=XTSL=XT............S1LS2L...SNL............

∂ L ∂ S i = [ ∂ L ∂ S i 1 ∂ L ∂ S i 2 . . . ∂ L ∂ S i C ] \frac{\partial L}{\partial S_i}=\begin{bmatrix} \frac{\partial L}{\partial S_{i1}}&\frac{\partial L}{\partial S_{i2}}&...&\frac{\partial L}{\partial S_{iC}} \end{bmatrix} SiL=[Si1LSi2L...SiCL]

因此只要将L依次对 s i j s_{ij} sij依次求导:
L i ∂ S i j = { 0 j ≠ y i , s j − s y i + Δ ⩽ 0 1 j ≠ y i , , s j − s y i + Δ > 0 − ( n u m ( j ≠ y i , , s j − s y i + Δ > 0 ) − 1 ) \frac{L_i}{\partial S_{ij}} =\left\{ \begin{aligned} 0 & &j\neq y_i,s_j-s_{y_i}+\Delta\leqslant0\\ 1 & &j\neq y_i,,s_j-s_{y_i}+\Delta>0 \\ -(num(j\neq y_i,,s_j-s_{y_i}+\Delta>0)-1) \end{aligned} \right. SijLi=01(numj=yi,,sjsyi+Δ>01)j=yi,sjsyi+Δ0j=yi,,sjsyi+Δ>0

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.                                                           #
  #############################################################################
  # note delta = 1
  print(X)
  num = X.shape[0]
  y_c = np.dot(X,W)
  score_y = y_c[range(num),y].reshape(num,1)
  margin = np.maximum(0,y_c-score_y+1)
  margin[range(num),y] =0
  loss += np.sum(margin)/num
  loss += 0.5 * 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.                                                                     #
  #############################################################################
  #first step :
  margin[margin > 0] = 1.0
  row_sum = np.sum(margin,axis = 1)
  margin[np.arange(num), y] = -row_sum
  dW += 1.0 / num * np.dot(X.T, margin) + reg * W
  #############################################################################
  #                             END OF YOUR CODE                              #
  #############################################################################

  return loss, dW
Naive loss and gradient: computed in 0.267549s
Vectorized loss and gradient: computed in 0.002870s
difference: 0.000000

果然速度还是快了很多!(以后都尽量用向量去写代码)

Stochastic Gradient Descent

from __future__ import print_function

import numpy as np
from cs231n.classifiers.linear_svm import *
from cs231n.classifiers.softmax import *

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 range(num_iters):
      X_batch = None
      y_batch = None

      #########################################################################
      # 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.              #
      #########################################################################
      batch_inx = np.random.choice(num_train, batch_size) #随机选5个
      X_batch = X[batch_inx,:]
      y_batch = y[batch_inx]
      #########################################################################
      #                       END OF YOUR CODE                                #
      #########################################################################

      # evaluate loss and gradient
      loss, grad = self.loss(X_batch, y_batch, reg)
      loss_history.append(loss)

      # perform parameter update
      #########################################################################
      # TODO:                                                                 #
      # Update the weights using the gradient and the learning rate.          #
      #########################################################################
      self.W += -learning_rate*grad
      #########################################################################
      #                       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])
    ###########################################################################
    # TODO:                                                                   #
    # Implement this method. Store the predicted labels in y_pred.            #
    ###########################################################################
    y = np.dot(X,self.W)
    y_pred += np.argmax(y,axis=1)
    ###########################################################################
    #                           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)


下面这步是用来寻找最优超参数的(算法还是比较简单的,就是找最高的accuracy)

# 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_rate = [2e-7,0.75e-7,1.5e-7,1.25e-7,0.75e-7]
regularization_strengths = [3e4,3.25e4,3.5e4,3.75e4,4e4]

# 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_val = -1   # The highest validation accuracy that we have seen so far.
best_svm = None # The LinearSVM object that achieved the highest validation rate.

################################################################################
# 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.                                      #
################################################################################
for rate in learning_rate:
    for regular in regularization_strengths:
        svm = LinearSVM()
        loss_hist = svm.train(X_train, y_train, learning_rate=rate, reg=regular,num_iters=2000, verbose=True)
        y_train_pred = svm.predict(X_train)
        y_val_pred = svm.predict(X_val)
        accuracy_train = np.mean(y_train == y_train_pred)
        accuracy_test = np.mean(y_val == y_val_pred)
        if best_val < accuracy:
            best_val = accuracy
            best_svm = svm
        results[(rate,regular)]=(accuracy_train,accuracy_test)

################################################################################
#                              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)

最后这部分代码很有意思,它显示表示了W的实际意义,某块的颜色更深,不同类的W要去寻找图片的模板,比如说horse的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])

在这里插入图片描述
第二次作业写了挺久,主要是gradient那里,还重新去看了好几遍书和知乎,最后终于搞懂了,撒花!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值