Stanford에서 강의하는 CS231n의 Assignment 1(3): Implement a Softmax classifier을 정리한 글입니다.
Inline Question 1
Why do we expect our loss to be close to -log(0.1)? Explain briefly.
Your Answer : 가중치(W)가 랜덤한 작은 값으로 초기화 되었기 때문에 score function의 모든 결과가 0에 가깝습니다. 따라서 첫 번째 iteration에서 loss는 $-log(\frac{1}{C})$ 에 가깝습니다. (C: number of classes) sanity check을 이용해 알고리즘이 잘 작동하는지 확인할 수 있습니다.
Inline Question 2
Suppose the overall training loss is defined as the sum of the per-datapoint loss over all training examples. It is possible to add a new datapoint to a training set that would leave the SVM loss unchanged, but this is not the case with the Softmax classifier loss.
Your Answer :
Your Explanation : Softmax classifier loss에서는 모든 학습 데이터가 영향을 미칩니다. ($Loss_{softmax}:-log(\frac{e^{sy_i}}{\sum e^{s_j}})$) 반면, SVM loss는 학습 데이터의 $s_{y_i}$(정답 클래스의 예측 점수)와 $s_j$(오답 클래스의 예측 점수)의 차이가 margin 이상으로 높을 때 loss가 발생한다.($s_j > s_{y_i}$ 인 경우에만) 반면, $s_{y_i} > s_j$ 이거나, 그 격차가 margin 보다 작을 때에는 학습 데이터 포인트의 loss는 0이다. 따라서, 해당 데이터 포인트를 추가하여도 loss는 변하지 않는다.
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)*****
for i in range(X.shape[0]):
score = X[i].dot(W)
exp_score = np.exp(score)
_softmax = exp_score[y[i]]/np.sum(exp_score)
for j in range(W.shape[1]):
dW[:,j] += np.exp(score[j])/np.sum(np.exp(score)) * X[i]
dW[:, y[i]] -= X[i]
loss -= np.log(_softmax)
loss /= X.shape[0]
dW /= X.shape[0]
loss += reg * np.sum(W*W)
dW += 2*reg*W
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return loss, dW
우선, softmax loss와 dw를 naive하게 구하는 방법입니다.
softmax loss 와 dw를 구하는 수식을 먼저 작성해 봅니다.
$$L_i = -log(\frac{e^{s_{y_i}}}{\sum e^{s_j}}) = -s_{y_i} + log(\sum e^{s_j})$$
1) $j = y_i$
$$\frac{\partial L}{\partial w_j} = -x_j + \frac{e^s_j \cdot x_j}{\sum e^s_j}$$
2) $j \neq y_i$
$$\frac{\partial L}{\partial w_j} = \frac{e^s_j \cdot x_j}{\sum e^s_j}$$
따라서, 데이터 셋 만큼 반복하면서 $w_j += \frac{e^s_j \cdot x_j}{\sum e^s_j}$ 를 반복해주고, 데이터 셋 별로 각각 한번씩 $w_{s_i} -= x_i$ 를 진행해주면 되겠습니다.
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! #
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
score = X.dot(W) # (500, 10)
exp_score = np.exp(score)
#loss
_softmax = exp_score / np.sum(exp_score,axis=1).reshape(-1,1)
loss = np.sum(-np.log(_softmax[np.arange(X.shape[0]), y]))
#dw
_softmax[np.arange(X.shape[0]), y] -= 1
dW += X.T.dot(_softmax)
loss /= X.shape[0]
dW /= X.shape[0]
loss += reg*np.sum(W*W)
dW += 2 * reg * W
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return loss, dW
반복문 없이 vectorized 함수로 loss와 dw를 한번에 구하는 함수 입니다.
loss는 생략하겠습니다.
앞서 naive하게 dw를 구하는 방법을 생각해보면, 한개의 데이터 포인트에서 $dw_j += \frac{e^s_j \cdot x_j}{\sum e^s_j}$을 class 개수 만큼 반복, $dw_{s_i} -= x_i$를 통해 구했습니다.
이 예시에서의 각 데이터들의 Shape은 다음과 같습니다.
# X.shape = (500, 3073)
# W.shape = (3073, 10) , dw.shape = (3073, 10)
# y.shape = (10,)
# softmax matrix.shape = (500, 10) ##softmax matrix = X.dot(W)
dw를 구하기 위해 softmax matrix를 이용합니다.
우선, 앞서 j번 째 class에 영향을 미치는 $w_j$는 $\frac{e^s_j \cdot x_j}{\sum e^s_j}$를 더해줘야 합니다. 이는 j번째 class가 정답일 확률 $\cdot$ $x_i$ 입니다. 이는 단순히 softmax matrix와 입력 matrix의 내적임으로 $X.T.dot(softmax matrix)$ 로 구할 수 있습니다.
다음으로, 정답 class인 $s_i$에 영향을 미치는 $w_{s_i}$는 입력 데이터를 한번씩 빼줘야합니다. 이는 softmax matrix와 입력 X를 내적하기 이전, softmax matrix의 정답 클래스의 확률에서 1을 빼주면 코드를 간소화 할 수 있습니다.
'Stanford CS231n' 카테고리의 다른 글
| CS231n Assignment 2(2) : BatchNormalization (0) | 2024.12.18 |
|---|---|
| CS231n Assignment 2(1) : Multi-Layer Fully Connected Neural Networks (1) | 2024.12.17 |
| CS231n Assignment 1(1) : K-Nearest Neighbor classifier (0) | 2024.12.04 |
| Lecture 11: Detection and Segmentation (1) | 2024.11.26 |
| Weight Initialization (0) | 2024.11.11 |