0
votes

I was trying to solve the CS 231n assignment 1 and had problems implementing gradient for softmax. Note, I'm not enrolled in the course and just doing it for learning purposes. I calculated the gradient by hand initially and it seems fine to me and I implemented the gradient as below, but when the code is run against numerical gradient the results are not matching, I want to understand where I'm going wrong in this implementation if someone could please help me clarify this clearly.

Thank you.

Code:

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
1

1 Answers

0
votes

I figured out the answer myself.

The line:

dW = dW / (denom_sum)

is an error. Also, modified the code to make it work.

    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

I was dividing all element by denom_sum earlier whereas I should have divided it column wise only.