1. 程式人生 > >cs231n作業:assignment1 - softmax

cs231n作業:assignment1 - softmax


title: cs231n作業:assignment1 - softmax
id: cs231n-1h-3
tags:

  • cs231n
  • homework
    categories:
  • AI
  • Deep Learning
    date: 2018-09-27 16:02:57

GitHub地址:https://github.com/ZJUFangzh/cs231n
個人部落格:fangzh.top
softmax是最常用的分類器之一。

softmax和svm都是常用的分類器,而softmax更為常用。

具體可以參考我這篇的最後,ng老師有講,

softmax

前面資料集的都跟SVM的一樣。

直接進入loss和grads推導環節。

L i = l o g

( e f y i
j
e f j
) L_i = -log(\frac{e^{f_{y_i}}}{\sum_j e^{f_j}})

可以看到,計算的公式也就是cross-entropy,即

H ( p , q ) = i y i l o g ( y i h a t ) H(p,q) = - \sum_i y_i log(y_{i}^{hat})

但是,這樣有一個缺點,就是指數 e f y i e^{f_{y_i}} 可能會特別大,這樣可能導致記憶體不足,計算不穩定等問題。那麼可以在分子分母同乘一個常數C,一般C取為 l o g C = m a x f j logC = -max f_j

f = np.array([123, 456, 789]) # 例子中有3個分類,每個評分的數值都很大
p = np.exp(f) / np.sum(np.exp(f)) # 不妙:數值問題,可能導致數值爆炸

# 那麼將f中的值平移到最大值為0:
f -= np.max(f) # f becomes [-666, -333, 0]
p = np.exp(f) / np.sum(np.exp(f)) # 現在OK了,將給出正確結果

精確地說,SVM分類器使用的是折葉損失(hinge loss),有時候又被稱為最大邊界損失(max-margin loss)。Softmax分類器使用的是交叉熵損失(corss-entropy loss)。Softmax分類器的命名是從softmax函式那裡得來的,softmax函式將原始分類評分變成正的歸一化數值,所有數值和為1,這樣處理後交叉熵損失才能應用。注意從技術上說“softmax損失(softmax loss)”是沒有意義的,因為softmax只是一個壓縮數值的函式。但是在這個說法常常被用來做簡稱。

求導過程參考:cs231n softmax求導

最終得到的公式是:

softmax程式碼實現

編輯cs231n/classifiers/softmax.py,先寫一下softmax_loss_naive函式,依舊是迴圈:

def softmax_loss_naive(W, X, y, reg):
  """
  Softmax 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
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)

  #############################################################################
  # TODO: Compute the softmax loss and its gradient using explicit loops.     #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
  #############################################################################
  (N, D) = X.shape
  C = W.shape[1]
  #遍歷每個樣本
  for i in range(N):
    f_i = X[i].dot(W)
    #進行公式的指數修正
    f_i -= np.max(f_i)
    sum_j = np.sum(np.exp(f_i))
    #得到樣本中每個類別的概率
    p = lambda k : np.exp(f_i[k]) / sum_j
    loss += - np.log(p(y[i]))
    #根據softmax求導公式
    for k in range(C):
      p_k = p(k)
      dW[:, k] += (p_k - (k == y[i])) * X[i]
  
  loss /= N
  loss += 0.5 * reg * np.sum(W * W)
  dW /= N
  dW += reg*W
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

驗證一下loss和grad得到:

numerical: -0.621593 analytic: -0.621593, relative error: 7.693773e-09
numerical: -2.576505 analytic: -2.576505, relative error: 4.492083e-09
numerical: -1.527801 analytic: -1.527801, relative error: 4.264914e-08
numerical: 1.101379 analytic: 1.101379, relative error: 9.735173e-09
numerical: 2.375620 analytic: 2.375620, relative error: 3.791861e-08
numerical: 3.166961 analytic: 3.166960, relative error: 8.526285e-09
numerical: -1.440997 analytic: -1.440998, relative error: 4.728898e-08
numerical: 0.563304 analytic: 0.563304, relative error: 2.409996e-08
numerical: -2.057292 analytic: -2.057292, relative error: 1.820335e-08
numerical: -0.450338 analytic: -0.450338, relative error: 8.075985e-08
numerical: -0.233090 analytic: -0.233090, relative error: 4.136546e-08
numerical: 0.251391 analytic: 0.251391, relative error: 4.552523e-08
numerical: 0.787031 analytic: 0.787031, relative error: 5.036469e-08
numerical: -1.801593 analytic: -1.801594, relative error: 3.159903e-08
numerical: -0.294108 analytic: -0.294109, relative error: 1.792497e-07
numerical: -1.974307 analytic: -1.974307, relative error: 1.160708e-08
numerical: 2.986921 analytic: 2.986921, relative error: 2.788065e-08
numerical: -0.247281 analytic: -0.247281, relative error: 8.957573e-08
numerical: 0.569337 analytic: 0.569337, relative error: 2.384912e-08
numerical: -1.579298 analytic: -1.579298, relative error: 1.728733e-08

向量化softmax

def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.

  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)

  #############################################################################
  # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
  #############################################################################
  (N, D) = X.shape
  C = W.shape[1]
  f = X.dot(W)
  #在列方向進行指數修正
  f -= np.max(f,axis=1,keepdims=True)
  #求得softmax各個類的概率
  p = np.exp(f) / np.sum(np.exp(f),axis=1,keepdims=True)
  y_lable = np.zeros((N,C))
  #y_lable就是(N,C)維的矩陣,每一行中只有對應的那個正確類別 = 1,其他都是0
  y_lable[np.arange(N),y] = 1
  #cross entropy
  loss = -1 * np.sum(np.multiply(np.log(p),y_lable)) / N
  loss += 0.5 * reg * np.sum( W * W)
  #求導公式,很清晰
  dW = X.T.dot(p-y_lable)
  dW /= N
  dW += reg*W


  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW


檢驗一下向量化和非向量化的時間:

naive loss: 2.357905e+00 computed in 0.091724s
vectorized loss: 2.357905e+00 computed in 0.002995s
Loss difference: 0.000000
Gradient difference: 0.000000

softmax的函式已經編寫完成了,接下來調一下學習率和正則化兩個超引數:

# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of over 0.35 on the validation set.
from cs231n.classifiers import Softmax
results = {}
best_val = -1
best_softmax = None
learning_rates = [1e-7, 5e-7]
regularization_strengths = [2.5e4, 5e4]

################################################################################
# TODO:                                                                        #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save    #
# the best trained softmax classifer in best_softmax.                          #
################################################################################
for lr in learning_rates:
    for reg in regularization_strengths:
        softmax = Softmax()
        loss_hist = softmax.train(X_train, y_train, learning_rate=lr, reg=reg,
                      num_iters=1500, verbose=True)
        y_train_pred = softmax.predict(X_train)
        y_val_pred = softmax.predict(X_val)
        y_train_acc = np.mean(y_train_pred==y_train)
        y_val_acc = np.mean(y_val_pred==y_val)
        results[(lr,reg)] = [y_train_acc, y_val_acc]
        if y_val_acc > best_val:
            best_val = y_val_acc
            best_softmax = softmax
################################################################################
#                              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)
lr 1.000000e-07 reg 2.500000e+04 train accuracy: 0.350592 val accuracy: 0.354000
lr 1.000000e-07 reg 5.000000e+04 train accuracy: 0.329551 val accuracy: 0.342000
lr 5.000000e-07 reg 2.500000e+04 train accuracy: 0.347286 val accuracy: 0.359000
lr 5.000000e-07 reg 5.000000e+04 train accuracy: 0.328551 val accuracy: 0.337000
best validation accuracy achieved during cross-validation: 0.359000