cs231n_Linear_svm

Linear_svm原理


SVM损失:计算了所有不正确的例子,将所有不正确类别的评分与正确类别评分之差再加1,将得到的数值与0比较,取二者最大,然后将所有数值进行求和。
计算分数:
s = f ( x , W ) = W x s=f(x,W)=Wx s=f(x,W)=Wx
计算完全损失(有正则项):

代码

主要是矩阵实现程序

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[:,y[i]]+=-X[i].T
        dW[:,j] +=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 += 2*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. #
  #############################################################################
# scores = X.dot(W)
# num_train = X.shape[0]
# correct_class_score = scores[np.arange(num_train),y]
# correct_class_score = np.reshape(correct_class_score,(num_train,-1))
# margin = scores - correct_class_score + 1
# np.maximum(margin,0) # 判断是否大于0
# margin[np.arange(num_train),y]=0
# loss += np.sum(margin)/num_train
# loss += reg * np.sum(W*W)
  scores = X.dot(W)
# num_classes = W.shape[1]
  num_train = X.shape[0]

  correct_class_score = scores[np.arange(num_train),y]
  correct_class_score = np.reshape(correct_class_score,(num_train,-1))
  margins = scores - correct_class_score + 1
  margins = np.maximum(margins,0)
  #然后这里计算了j=y[i]的情形,所以把他们置为0
  margins[np.arange(num_train),y] = 0
  loss += np.sum(margins) / num_train
  loss += 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. #
  #############################################################################
# num_classes = W.shape[1]
# mask_margin = np.zeros((num_train, num_classes)) # where margin[i,j]>0=1
# mask_margin[margin>0] = 1
# mask_XW = np.ones((num_train, num_classes))
# mask_XW = mask_XW * mask_margin
# y_sum = np.sum(mask_margin, axis=1)
# print(y_sum.shape)
# mask_XW[np.arange(num_train), y] -= y_sum
# dW = np.dot(X.T, mask_XW)/num_train
# dW += 2 * reg * W

  margins[margins > 0] = 1
  margins[margins <=0] = 0
  row_sum = np.sum(margins, axis=1)
  margins[np.arange(num_train),y] -= row_sum
  dW = np.dot(X.T, margins)
  dW /= num_train
  dW += 2*reg*W
  #############################################################################
  # END OF YOUR CODE #
  #############################################################################

  return loss, dW

小tips

  1. numpy可以直接两重索引替换值
    arr[arr1,arr2] = 0,即使得arr[arr1[0]][arr2[0]]=0, arr[arr1[1]][arr2[1]]=0…