Stanford cs231n Assignment #1 (b) 实现SVM

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

1. Preprocessing

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

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所要求的间隔):

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是一个正数,那么自变量就是正向作用,它越大则目标函数值越大,那么我们为了得到极小值,是不是就应该按照反方向来对权值(自变量)进行调整呢?恩~

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的单层训练器的有效性可想而知嘛。想说的是最后的一步可视化:

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

4DFDU.png

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容