全球名校课程作业分享系列(2)--斯坦福计算机视觉与深度学习CS231n之SVM图像分类

课程作业原地址:CS231n Assignment 1
作业及整理:@谭斌 && @Molly && @寒小阳
时间:2018年1月。
出处:http://blog.csdn.net/han_xiaoyang/article/details/70214565

任务背景

用支持向量机(SVM)的方法去完成图像识别多分类的任务

  • 完成一个基于SVM的全向量化损失函数
  • 完成解析梯度的全向量化表示
  • 用数值梯度来验证你的实现
  • 使用一个验证集去调优学习率和正则化强度
  • 运用随机梯度下降优化损失函数
  • 可视化最后的学习得到的权重

线性SVM分类器

可以简单地认为,线性分类器给样本分类,每一个可能类一个分数,正确的分类分数,应该比错误的分类分数大.为了使分类器在分类未知样本的时候,鲁棒性更好一点,我们希望正确分类的分数比错误分类分数大得多一点.所以我们设置一个阈值 Δ ,让正确分类的分数至少比错误分数大 Δ ,这是我们期望的安全距离。这就得到了hinge损失函数.

Li=jyimax(0,SjSyi+Δ)
其中, Li 表示第i个样本的loss函数. Syi 表示第i个样本正确分类的标签的分数, Sj 表示第i个样本对应某个标签的分数. 当我们将线性方程 f(x)=wTx+b 的系数乘以一个倍数之后,得分将全部乘以这个倍数.所以 Δ 的值具体多少是没有意义的,有意义的是它相对于其他类上得分的大小,所以这里可以直接设定为1.如果想获得更专业的数学表达,可以查看周志华老师的《机器学习》等书籍。

然后再加入一个正则项来衡量模型的复杂度,学过线性回归的同学自然想到正则化的L1或者L2正则,比如 12||w||2 ,然后目标函数就变成:

Li=jyimax(0,SjSyi+Δ)+λ2||w||2
到了这一步,基本上能看出一些与传统机器学习推导SVM公式的思路异曲同工的地方了,至于求解,用SGD就可以了。
以上,就是本次多分类SVM的一些心得,要细究起来,水还是很深的。

notebook的一些预备代码

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

from __future__ import print_function

#基本设定 让matplotlib画的图出现在notebook页面上,而不是新建一个画图窗口.
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # 设置默认的绘图窗口大小
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

# 另一个设定 可以使notebook自动重载外部python 模块.[点击此处查看详情][4]
# 也就是说,当从外部文件引入的函数被修改之后,在notebook中调用这个函数,得到的被改过的函数.
%load_ext autoreload
%autoreload 2

加载CIFAR-10原始数据

# 这里加载数据的代码在 data_utils.py 中,会将data_batch_1到5的数据作为训练集,test_batch作为测试集
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)

# 为了对数据有一个认识,打印出训练集和测试集的大小 
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()

输出

将数据分割为训练集,验证集和测试集。

另外我们将创建一个小的“开发集”作为训练集的子集,算法开发时可以使用这个开发集,使我们的代码运行更快。
个人看法,这个development set在这个note book里,就是从训练集中进行了一个小的抽样,用来测试一些结论。
在吴恩达老师的深度学习课程和其他一些书籍里,development set 应该是被等同于验证集的,这里说明下。

num_training = 49000
num_validation = 1000
num_test = 1000
num_dev = 500

# 验证集将会是从原始的训练集中分割出来的长度为 num_validation 的数据样本点
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]

# 训练集是原始的训练集中前 num_train 个样本
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]

# 我们也可以从训练集中随机抽取一小部分的数据点作为开发集
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]

# 使用前 num_test 个测试集点作为测试集
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,)

数据预处理,将原始数据转成二维数据

#np.reshape(input_array, (k,-1)), 其中k为除了最后一维的维数,-1表示并不人为指定,由k和原始数据的大小来确定最后一维的长度.
#将所有样本,各自拉成一个行向量,所构成的二维矩阵,每一行就是一个样本,即一行有32X32X3个数,每个数表示一个特征。

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

# 很正常地,要打印出来数据的形状看看。
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)

预处理,减去图像的平均值

# 首先,基于训练数据,计算图像的平均值
mean_image = np.mean(X_train, axis=0)#计算每一列特征的平均值,共32x32x3个特征
print(mean_image.shape)
print(mean_image[:10]) # 查看一下特征的数据
plt.figure(figsize=(4,4))#指定画图的框图大小
plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # 将平均值可视化出来。
plt.show()

输出

(3072,)
[ 130.64189796  135.98173469  132.47391837  130.05569388  135.34804082
  131.75402041  130.96055102  136.14328571  132.47636735  131.48467347]

# 然后: 训练集和测试集图像分别减去均值#
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
X_dev -= mean_image
# 最后,在X中添加一列1作为偏置维度,这样我们在优化时候只要考虑一个权重矩阵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)
#看看各个数据集的shape,可以看出多了一列

输出

(49000, 3073) (1000, 3073) (1000, 3073) (500, 3073)

SVM 分类器

这部分的code在 xxx/cs231n/classifiers/linear_svm.py 里,请按要求补充
我们已经实现了一个compute_loss_naive 方法,使用循环实现的loss计算.

# 评估我们提供给你的loss的朴素的实现.

from cs231n.classifiers.linear_svm import svm_loss_naive
import time

# 生成一个很小的SVM随机权重矩阵
# 真的很小,先标准正态随机然后乘0.0001
W = np.random.randn(3073, 10) * 0.0001 

loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.000005)  # 从dev数据集种的样本抽样计算的loss是。。。大概估计下多少,随机几次,loss在8至9之间
print('loss: %f' % (loss, ))

输出

loss: 9.417096

上面返回的grad现在全是0.推导并实现SVM损失函数,写在svm_loss_native方法中.

为了检验你是否已经正确地实现了梯度算法,你可以用数值方法估算损失函数的梯度,然后比较数值与你用方程计算的值,我们在下方提供了代码。

linear_svm.py

def svm_loss_naive(W, X, y, reg):
  """
    使用循环实现的SVM loss 函数。
    输入维数为D,有C类,我们使用N个样本作为一批输入。
    输入:
    -W: 一个numpy array,形状为 (D, C) ,存储权重。
    -X: 一个numpy array, 形状为 (N, D),存储一个小批数据。
    -y: 一个numpy array,形状为 (N,), 存储训练标签。y[i]=c 表示 x[i]的标签为c,其中 0 <= c <= C 。
    -reg: float, 正则化强度。

    输出一个tuple:
    - 一个存储为float的loss
    - 权重W的梯度,和W大小相同的array
  """
  dW = np.zeros(W.shape) # 梯度全部初始化为0
  # 计算损失和梯度
  num_classes = W.shape[1]
  num_train = X.shape[0]
  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]:
        continue
      margin = scores[j] - correct_class_score + 1 # 记住 delta = 1
      if margin > 0:
        loss += margin
        dW[:, y[i]] += -X[i, :].T    
        dW[:, j] += X[i, :].T        

    # 现在损失函数是所有训练样本的和.但是我们要的是它们的均值.所以我们用 num_train 来除.

  loss /= num_train
  dW /= num_train
  # 加入正则项
  loss +=  reg * np.sum(W * W)
  dW += reg * W

#############################################################################
  # 任务:                                                         
  # 计算损失函数的梯度并存储在dW中. 相比于先计算loss然后计算梯度,
  # 同时计算梯度和loss会更加简单.所以你可能需要修改上面的代码,来计算梯度  
#############################################################################

  return loss, dW

验证梯度结果

回到notebook.


# 实现梯度之后,运行下面的代码重新计算梯度.
# 输出是grad_check_sparse函数的结果,2种情况下,可以看出,其实2种算法误差已经几乎不计了。。。
loss, grad = svm_loss_naive(W, X_dev, y_dev, 0.0)

# 对随机选的几个维度计算数值梯度,并把它和你计算的解析梯度比较.所有维度应该几乎相等.
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)

# 再次验证梯度.这次使用正则项.你肯定没有忘记正则化梯度吧~
print('turn on reg')
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: -5.807950 analytic: -5.807950, relative error: 1.828298e-11
numerical: -14.928666 analytic: -14.928666, relative error: 9.989241e-12
numerical: 1.059552 analytic: 1.059552, relative error: 6.114175e-11
numerical: -29.481796 analytic: -29.481796, relative error: 5.863187e-13
numerical: 23.762741 analytic: 23.762741, relative error: 1.351804e-11
numerical: 8.872796 analytic: 8.872796, relative error: 2.925921e-11
numerical: -2.480627 analytic: -2.480627, relative error: 1.035958e-10
numerical: 7.650113 analytic: 7.589849, relative error: 3.954297e-03
numerical: 24.438469 analytic: 24.438469, relative error: 1.619239e-11
numerical: 0.781688 analytic: 0.781688, relative error: 6.861017e-11
turn on reg
numerical: 4.243960 analytic: 4.268399, relative error: 2.871033e-03
numerical: -22.515384 analytic: -22.510695, relative error: 1.041591e-04
numerical: 18.283080 analytic: 18.286599, relative error: 9.622179e-05
numerical: 0.401949 analytic: 0.348694, relative error: 7.094580e-02
numerical: 28.537163 analytic: 28.535275, relative error: 3.308435e-05
numerical: -22.447485 analytic: -22.448065, relative error: 1.291663e-05
numerical: 0.700087 analytic: 0.701799, relative error: 1.221305e-03
numerical: 5.775369 analytic: 5.774106, relative error: 1.093817e-04
numerical: -4.901730 analytic: -4.911853, relative error: 1.031485e-03
numerical: 9.014401 analytic: 9.011687, relative error: 1.505957e-04

随堂练习1:

偶尔会出现梯度验证时候,某个维度不一致,导致不一致的原因是什么呢?这是我们要考虑的一个因素么?梯度验证失败的简单例子是?
提示:SVM 损失函数没有被严格证明是可导的.
可以看上面的输出结果,turn on reg前有一个是3.954297e-03的loss明显变大.

参考答案
解析解和数值解的区别,数值解是用前后2个很小的随机尺度(比如0.00001)进行计算,当Loss不可导的,两者会出现差异。比如 Syi 刚好比 Sj 大1.

完成 svm_loss_vectorized 方法

现在先计算loss,等一下完成梯度

linear_svm.py

def svm_loss_vectorized(W, X, y, reg):
  """
    结构化的SVM损失函数,使用向量来实现.
    输入和输出和svm_loss_naive一致.
  """
  loss = 0.0
  dW = np.zeros(W.shape) # 初始化梯度为0

  #############################################################################
  # 任务:                                                                     #
  # 实现结构化SVM损失函数的向量版本.将损失存储在loss变量中.                 #
  #############################################################################

  scores = X.dot(W)        
  num_classes = W.shape[1]
  num_train = X.shape[0]

  scores_correct = scores[np.arange(num_train), y] 
  scores_correct = np.reshape(scores_correct, (num_train, -1)) 
  margins = scores - scores_correct + 1
  margins = np.maximum(0,margins)
  margins[np.arange(num_train), y] = 0
  loss += np.sum(margins) / num_train
  loss += 0.5 * reg * np.sum(W * W)
  #############################################################################
  #                            代码结束                              #
  #############################################################################



  #############################################################################
  # 任务:                                                                     #
  # 使用向量计算结构化SVM损失函数的梯度,把结果保存在 dW.                    #
  # 提示:不一定从头计算梯度,可能重用计算loss时的一些中间结果会更简单.      #
  #############################################################################

  margins[margins > 0] = 1
  row_sum = np.sum(margins, axis=1)                  # 1 by N
  margins[np.arange(num_train), y] = -row_sum        
  dW += np.dot(X.T, margins)/num_train + reg * W     # D by C

  #############################################################################
  #                             代码结束                              #
  #############################################################################
  return loss, dW

回到notebook.

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

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

# The losses should match but your vectorized implementation should be much faster.
print('difference: %f' % (loss_naive - loss_vectorized))

输出:

Naive loss: 9.417096e+00 computed in 0.121770s
Vectorized loss: 9.417096e+00 computed in 0.005394s
difference: 0.000000
# 使用向量来计算损失函数的梯度.
# 朴素方法和向量法的结果应该是一样的,但是向量法会更快一点.

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)
Naive loss and gradient: computed in 0.127225s
Vectorized loss and gradient: computed in 0.003415s
difference: 0.000000

随机梯度下降

我们已经向量化并且高效地表达了损失、梯度,而且我们的梯度是与梯度数值解相一致的。因此我们可以利用SGD来最小化损失了。

linear_classifier.py

在文件 linear_classifier.py 里,完成SGD函数 LinearClassifier.train()

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.
使用随机梯度下降来训练这个分类器。
输入:
-X:一个 numpy array,形状为 (N, D), 存储训练数据。 共N个训练数据, 每个训练数据是N维的。
-Y:一个 numpy array, 形状为(N,), 存储训练数据的标签。y[i]=c 表示 x[i]的标签为c,其中 0 <= c <= C 。
-learning rate: float, 优化的学习率。
-reg:float, 正则化强度。
-num_iters: integer, 优化时训练的步数。
-batch_size: integer, 每一步使用的训练样本数。
-verbose: boolean,若为真,优化时打印过程。
输出:
一个存储每次训练的损失函数值的list。
"""

num_train, dim = X.shape
num_classes = np.max(y) + 1 # 假设y的值是0...K-1,其中K是类别数量。

if self.W is None:
  # 简易初始化 W
  self.W = 0.001 * np.random.randn(dim, num_classes)

# 使用随机梯度下降优化W
loss_history = []
for it in xrange(num_iters):
  X_batch = None
  y_batch = None

  #########################################################################
  # 任务: 
  # 从训练集中采样batch_size个样本和对应的标签,在这一轮梯度下降中使用。
  # 把数据存储在 X_batch 中,把对应的标签存储在 y_batch 中。
  # 采样后,X_batch 的形状为 (dim, batch_size),y_batch的形状为(batch_size,)
  #  
  # 提示:用 np.random.choice 来生成 indices。有放回采样的速度比无放回采
  # 样的速度要快。
  #########################################################################
  batch_inx = np.random.choice(num_train, batch_size)
  X_batch = X[batch_inx,:]
  y_batch = y[batch_inx]
  #########################################################################
  #                       结束                                #
  #########################################################################

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

  # perform parameter update
  #########################################################################
  # TODO:                                                                 #
  # 使用梯度和学习率更新权重
  #########################################################################
  self.W = self.W - learning_rate * grad
  #########################################################################
  #                      结束                               #
  #########################################################################

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

return loss_history

回到notebook。

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=1500, verbose=True)
toc = time.time()
print('That took %fs' % (toc - tic))
iteration 0 / 1500: loss 406.551290
iteration 100 / 1500: loss 240.613943
iteration 200 / 1500: loss 146.111274
iteration 300 / 1500: loss 90.213982
iteration 400 / 1500: loss 56.328602
iteration 500 / 1500: loss 35.504821
iteration 600 / 1500: loss 23.727488
iteration 700 / 1500: loss 15.755706
iteration 800 / 1500: loss 11.425011
iteration 900 / 1500: loss 9.055450
iteration 1000 / 1500: loss 7.637563
iteration 1100 / 1500: loss 6.671778
iteration 1200 / 1500: loss 5.914076
iteration 1300 / 1500: loss 5.219254
iteration 1400 / 1500: loss 5.034812
That took 3.781817s

回到notebook。

# 大佬说了,有效的debug策略就是将损失和循环次数画出来。
plt.plot(loss_hist)
plt.xlabel('Iteration number')
plt.ylabel('Loss value')
plt.show()

# 编写函数 LinearSVM.predict,评估训练集和验证集的表现。
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.380776
validation accuracy: 0.392000

使用验证集去调整超参数(正则化强度和学习率)

# 使用验证集去调整超参数(正则化强度和学习率),你要尝试各种不同的学习率
# 和正则化强度,如果你认真做,将会在验证集上得到一个分类准确度大约是0.4的结果。
# 设置学习率和正则化强度,多设几个靠谱的,可能会好一点。
# 可以尝试先用较大的步长搜索,再微调。

learning_rates = [2e-7, 0.75e-7,1.5e-7, 1.25e-7, 0.75e-7]
regularization_strengths = [3e4, 3.25e4, 3.5e4, 3.75e4, 4e4,4.25e4, 4.5e4,4.75e4, 5e4]


# 结果是一个词典,将形式为(learning_rate, regularization_strength) 的tuples 和形式为 (training_accuracy, validation_accuracy)的tuples 对应上。准确率就简单地定义为数据集中点被正确分类的比例。

results = {}
best_val = -1   # 出现的正确率最大值
best_svm = None # 达到正确率最大值的svm对象

################################################################################
# 任务:                                                                        #
# 写下你的code ,通过验证集选择最佳超参数。对于每一个超参数的组合,
# 在训练集训练一个线性svm,在训练集和测试集上计算它的准确度,然后
# 在字典里存储这些值。另外,在 best_val 中存储最好的验证集准确度,
# 在best_svm中存储达到这个最佳值的svm对象。
#
# 提示:当你编写你的验证代码时,你应该使用较小的num_iters。这样SVM的训练模型
# 并不会花费太多的时间去训练。当你确认验证code可以正常运行之后,再用较大的
# num_iters 重跑验证代码。

################################################################################
for rate in learning_rates:
    for regular in regularization_strengths:
        svm = LinearSVM()
        svm.train(X_train, y_train, learning_rate=rate, reg=regular,
                      num_iters=1000)
        y_train_pred = svm.predict(X_train)
        accuracy_train = np.mean(y_train == y_train_pred)
        y_val_pred = svm.predict(X_val)
        accuracy_val = np.mean(y_val == y_val_pred)
        results[(rate, regular)]=(accuracy_train, accuracy_val)
        if (best_val < accuracy_val):
            best_val = accuracy_val
            best_svm = svm
################################################################################
#                              结束                               #
################################################################################

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 7.500000e-08 reg 3.000000e+04 train accuracy: 0.367980 val accuracy: 0.378000
lr 7.500000e-08 reg 3.250000e+04 train accuracy: 0.374653 val accuracy: 0.382000
lr 7.500000e-08 reg 3.500000e+04 train accuracy: 0.374980 val accuracy: 0.376000
lr 7.500000e-08 reg 3.750000e+04 train accuracy: 0.374000 val accuracy: 0.377000
lr 7.500000e-08 reg 4.000000e+04 train accuracy: 0.371694 val accuracy: 0.378000
lr 7.500000e-08 reg 4.250000e+04 train accuracy: 0.374082 val accuracy: 0.374000
lr 7.500000e-08 reg 4.500000e+04 train accuracy: 0.372673 val accuracy: 0.382000
lr 7.500000e-08 reg 4.750000e+04 train accuracy: 0.374388 val accuracy: 0.373000
lr 7.500000e-08 reg 5.000000e+04 train accuracy: 0.374367 val accuracy: 0.376000
lr 1.250000e-07 reg 3.000000e+04 train accuracy: 0.374061 val accuracy: 0.359000
lr 1.250000e-07 reg 3.250000e+04 train accuracy: 0.373041 val accuracy: 0.388000
lr 1.250000e-07 reg 3.500000e+04 train accuracy: 0.373592 val accuracy: 0.390000
lr 1.250000e-07 reg 3.750000e+04 train accuracy: 0.375327 val accuracy: 0.370000
lr 1.250000e-07 reg 4.000000e+04 train accuracy: 0.371918 val accuracy: 0.391000
lr 1.250000e-07 reg 4.250000e+04 train accuracy: 0.369347 val accuracy: 0.372000
lr 1.250000e-07 reg 4.500000e+04 train accuracy: 0.370796 val accuracy: 0.374000
lr 1.250000e-07 reg 4.750000e+04 train accuracy: 0.370041 val accuracy: 0.382000
lr 1.250000e-07 reg 5.000000e+04 train accuracy: 0.367898 val accuracy: 0.372000
lr 1.500000e-07 reg 3.000000e+04 train accuracy: 0.371592 val accuracy: 0.387000
lr 1.500000e-07 reg 3.250000e+04 train accuracy: 0.373327 val accuracy: 0.405000
lr 1.500000e-07 reg 3.500000e+04 train accuracy: 0.366429 val accuracy: 0.380000
lr 1.500000e-07 reg 3.750000e+04 train accuracy: 0.371714 val accuracy: 0.392000
lr 1.500000e-07 reg 4.000000e+04 train accuracy: 0.365327 val accuracy: 0.367000
lr 1.500000e-07 reg 4.250000e+04 train accuracy: 0.366980 val accuracy: 0.371000
lr 1.500000e-07 reg 4.500000e+04 train accuracy: 0.360286 val accuracy: 0.378000
lr 1.500000e-07 reg 4.750000e+04 train accuracy: 0.362673 val accuracy: 0.378000
lr 1.500000e-07 reg 5.000000e+04 train accuracy: 0.363429 val accuracy: 0.376000
lr 2.000000e-07 reg 3.000000e+04 train accuracy: 0.375224 val accuracy: 0.367000
lr 2.000000e-07 reg 3.250000e+04 train accuracy: 0.371286 val accuracy: 0.385000
lr 2.000000e-07 reg 3.500000e+04 train accuracy: 0.368449 val accuracy: 0.378000
lr 2.000000e-07 reg 3.750000e+04 train accuracy: 0.360633 val accuracy: 0.371000
lr 2.000000e-07 reg 4.000000e+04 train accuracy: 0.360653 val accuracy: 0.363000
lr 2.000000e-07 reg 4.250000e+04 train accuracy: 0.363143 val accuracy: 0.375000
lr 2.000000e-07 reg 4.500000e+04 train accuracy: 0.361551 val accuracy: 0.362000
lr 2.000000e-07 reg 4.750000e+04 train accuracy: 0.356163 val accuracy: 0.354000
lr 2.000000e-07 reg 5.000000e+04 train accuracy: 0.351714 val accuracy: 0.357000
best validation accuracy achieved during cross-validation: 0.405000

 可视化交叉验证结果


import math
x_scatter = [math.log10(x[0]) for x in results]
y_scatter = [math.log10(x[1]) for x in results]

#画出训练准确率
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')

#画出验证准确率
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.tight_layout() # 调整子图间距
plt.show()

在测试集上评价最好的svm的表现

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.382000

结果偏低,不过考虑到是一个10分类问题,均匀分布下,乱猜的结果是0.1,所以还是有那么一点意思的。

#对于每一类,可视化学习到的权重
#依赖于你对学习权重和正则化强度的选择,这些可视化效果或者很明显或者不明显。
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])

随堂练习 2:

描述你的SVM可视化图像,给出一个简单的解释
参考答案:
将学习到的权重可视化,从图像可以看出,权重是用于对原图像进行特征提取的工具,与原图像关系很大。很朴素的思想,在分类器权重向量上投影最大的向量得分应该最高,训练样本得到的权重向量,最好的结果就是训练样本提取出来的共性的方向,类似于一种模板或者过滤器。

猜你喜欢

转载自blog.csdn.net/yaoqiang2011/article/details/79138402
今日推荐