【问题标题】:CS 231n: Gradient of Softmax Implementation ErrorCS 231n:Softmax 实现误差的梯度
【发布时间】:2021-04-01 19:23:53
【问题描述】:

我试图解决 CS 231n 作业 1 并且在实现 softmax 的梯度时遇到了问题。请注意,我没有注册该课程,只是为了学习目的。我最初是手动计算梯度的,对我来说似乎很好,我实现了如下梯度,但是当代码针对数值梯度运行时,结果不匹配,我想了解我在这个实现中哪里出错了有人可以帮我澄清一下。

谢谢。

代码:

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!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    num_train = X.shape[0]
    for i in range(num_train):
      score = X[i].dot(W)
      correct = y[i]
      denom_sum = 0.0
      num = 0.0
      
      for j,s in enumerate(score):
        denom_sum += np.exp(s)
        if j == correct:
          num = np.exp(s)
        else:
          dW[:,j] = X[i].T * np.exp(s) 
      loss += -np.log(num / denom_sum)
      dW[:, correct] += -X[i].T *  ( (denom_sum - num) )
      dW = dW / (denom_sum)

    loss = loss / (num_train)
    dW /= num_train
    loss += reg * np.sum(W * W)
    dW += reg * 2 * W
    return loss, dW

【问题讨论】:

    标签: python numpy deep-learning softmax


    【解决方案1】:

    我自己想出了答案。

    行:

    dW = dW / (denom_sum)
    

    是一个错误。 此外,修改了代码以使其工作。

        denom_sum = np.sum(np.exp(score))
        for j,s in enumerate(score):
          if j == correct:
            num = np.exp(s)
            dW[:, correct] += -X[i].T * ((denom_sum - num)/ (denom_sum))
          else:
            dW[:,j] += X[i].T * (np.exp(s) / denom_sum) 
        loss += -np.log(num / denom_sum)
      
      loss = loss / (num_train)
      dW /= num_train
      loss += reg * np.sum(W * W)
      dW += reg * 2 * W
    

    我之前将所有元素除以denom_sum,而我应该只按列划分。

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多