Stanford cs231n Assignment #1 (b) 实现SVM

上一章完成了一个KNN Classifier,这一章就来到了熟悉又陌生的SVM...感觉自己虽然以前用过SVM,但是从来没有真正搞懂过,就着这门好课巩固一下吧!

1. Preprocessing

和上一章不同的是,先visualize mean image:

Stanford cs231n Assignment #1 (b) 实现SVM_第1张图片
Paste_Image.png

然后从所有image中减去这个mean image,这个数据预处理过程是为了统一数据的量级。对于图像而言,像素值一定在0-255之间,所以直接减去mean就可以了,但是如果是其他数据,通常用标准化或者归一化来做。下面代码为预处理过程:

# 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

增加bias

# 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

2. implement a fully-vectorized loss function for the SVM

注意SVM的loss function, 这里的delta设置为1(即SVM所要求的间隔):

Stanford cs231n Assignment #1 (b) 实现SVM_第2张图片
Paste_Image.png

naive implementation

首先看一下naive的for loop解法,只要正常计算 dL/dW就可以了,这个没什么难度。需要稍微解释一下的是,代码中的dW其实是实际意义的dL/dW。
按照求导表达式为:
dW[:,j] += X[i].transpose()
dW[:,y[i]] -= X[i]

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
      # dW[:,j] += X[i].transpose()
      if margin > 0:
        loss += margin
        dW[:,j] += X[i].transpose()
        dW[:,y[i]] -= X[i]

  # 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)
  dW += reg * np.sum(W)

  return loss, dW

vectorized implementation

接下来看vectorized version:

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
  num_train = X.shape[0]
  num_classes = W.shape[1]

  #############################################################################
  # TODO:                                                                     #
  # Implement a vectorized version of the structured SVM loss, storing the    #
  # result in loss.                                                           #
  #############################################################################
  scores = X.dot(W)
  # true labels
  s_yi = scores[np.arange(num_train), y]
  mat = scores - np.tile(s_yi, (num_classes,1)).transpose() + 1
  loss_mat = np.maximum(np.zeros((num_train, num_classes)), mat)
  # loss_mat[loss_mat<0] = 0    # this worked out as well
  loss_mat[np.arange(num_train), y] = 0
  loss = np.sum(loss_mat)/num_train
  loss += 0.5 * reg * np.sum(W * W)

    #############################################################################
  # 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.                                                                     #
  #############################################################################
 
  # I don't know what's wrong about the following commented code
  #############################################################################
  # loss_pos = np.array(np.nonzero(loss_mat))
  # print loss_pos, loss_pos.shape
  # dW[ :, y[loss_pos[0,:]] ] -= X[ loss_pos[0,:],: ].transpose()
  # dW[ :, loss_pos[1,:] ] += X[ loss_pos[0,:],: ].transpose()
  # dW /= num_train
  # dW += reg * W

# Binarize into integers
  binary = loss_mat
  binary[loss_mat > 0] = 1

  # Perform the two operations simultaneously
  # (1) for all j: dW[j,:] = sum_{i, j produces positive margin with i} X[:,i].T
  # (2) for all i: dW[y[i],:] = sum_{j != y_i, j produces positive margin with i} -X[:,i].T
  col_sum = np.sum(binary, axis=1)
  binary[range(num_train), y] = -col_sum[range(num_train)]
  dW = np.dot(X.T, binary)

  # Divide
  dW /= num_train

  # Regularize
  dW += reg*W

  return loss, dW

一开始我自己实现的代码是代码中我说我不知道哪里错了的部分..到现在我也觉得是对的,还没有看出到底哪里错了,如果有人刚好看到这篇文章愿意指正出来,我会非常感谢您。第二种方法是在github上看到的一种方法,也很巧妙,搬过来用了发现代码跑的结果是对的,但是还是不明白为什么自己那个方法是错的QAQ...

3. Stochastic Gradient Descent (SGD)

每一次迭代训练的时候随机选取一个batch_size的数据个数。在给定的样本集合M中,随机取出副本N代替原始样本M来作为全集,对模型进行训练,这种训练由于是抽取部分数据,所以有较大的几率得到的是,一个局部最优解,但是一个明显的好处是,如果在样本抽取合适范围内,既会求出结果,而且速度还快。这个理解摘自:http://www.cnblogs.com/gongxijun/p/5890548.html

顺便发现了一个这个课程的bug,就是前面单纯实现svm的optimization的时候和后面做SGD的时候要求输入的数据维度是反着的……所以做这里的时候还把前面给改了……anyway……

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):
      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.              #
      #########################################################################
      num_random = np.random.choice(num_train, batch_size, replace=True)
      X_batch = X[num_random, :].transpose()
      # print X_batch.shape
      y_batch = y[num_random]
      #########################################################################
      #                       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 += -grad * learning_rate
      #########################################################################
      #                       END OF YOUR CODE                                #
      #########################################################################

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

    return loss_history

注意按照grad的反方向调整W!你想啊,这个grad代表的意义是,每正向改变w的值,会造成最终的目标函数有多大的改变。比如这个grad是一个正数,那么自变量就是正向作用,它越大则目标函数值越大,那么我们为了得到极小值,是不是就应该按照反方向来对权值(自变量)进行调整呢?恩~

Stanford cs231n Assignment #1 (b) 实现SVM_第3张图片
Paste_Image.png

4. Play with hyperparameters

至于怎么决定那些learning_rate, regularization_parameter的大小,就是用cross-validation集做验证的事了,将不同的参数用train来训练好后用X_val, y_val来做验证,然后选出正确率最高的一组参数。这里就不细说了,一些dirty work...最后的正确率也就是0.35-0.4罢了,这个svm的单层训练器的有效性可想而知嘛。想说的是最后的一步可视化:

Stanford cs231n Assignment #1 (b) 实现SVM_第4张图片
Paste_Image.png

的确是,很难看呢!!!

5 Hinge Loss

The Hinge Loss 定义为 E(z) = max(0,1-z)。Hinge loss是凸的,但是因为导数不连续,还有一些变种,比如 Squared Hing Loss (L2 SVM)。Hinge loss是下图的绿线。黑线是0-1函数,红线是log loss(基于最大似然的负log)。

Stanford cs231n Assignment #1 (b) 实现SVM_第5张图片
4DFDU.png

一般来讲,Hinge于soft-margin svm算法;log于LR算法(Logistric Regression);squared loss,也就是最小二乘法,于线性回归(Liner Regression);基于指数函数的loss于Boosting。

你可能感兴趣的:(Stanford cs231n Assignment #1 (b) 实现SVM)