Skip to content

Commit

Permalink
[feat] implement 'svm_loss_vectorized' function #1
Browse files Browse the repository at this point in the history
  • Loading branch information
jeongjae96 committed Feb 6, 2023
1 parent 5a5a08b commit 747956e
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions cs231n_2022/assignment1/cs231n/classifiers/linear_svm.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,15 @@ def svm_loss_vectorized(W, X, y, reg):
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

pass
num_train = X.shape[0]

scores = np.matmul(X, W)
correct_class_scores = scores[range(num_train), y].reshape(-1, 1)

margins = np.maximum(0, scores - correct_class_scores + 1)
margins[range(num_train), y] = 0

loss = np.sum(margins) / num_train + reg * np.sum(W * W)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

Expand All @@ -98,8 +106,13 @@ def svm_loss_vectorized(W, X, y, reg):
# loss. #
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

# ref: https://mainpower4309.tistory.com/28
dScores = np.zeros(scores.shape)
dScores[margins > 0] = 1
dScores[range(num_train), y] -= np.sum(dScores, axis=1)

pass
dW = np.matmul(X.T, dScores) / num_train + 2 * reg * W

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

Expand Down

0 comments on commit 747956e

Please sign in to comment.