-
Notifications
You must be signed in to change notification settings - Fork 0
/
softmax.py
98 lines (82 loc) · 3.93 KB
/
softmax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange
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)
num_train = X.shape[0]
num_dims = W.shape[0]
num_classes = W.shape[1]
#############################################################################
# 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 training_example_index in range(num_train):
# Compute cross-entropy loss
raw_scores = X[training_example_index].dot(W)
raw_scores -= np.max(raw_scores) # Prevent numerical instability for Softmax computation
softmax_scores = np.exp(raw_scores) / np.sum(np.exp(raw_scores))
loss += -np.log(softmax_scores[y[training_example_index]])
# Compute gradient. Mathematical explanation here: https://stackoverflow.com/a/67046905/13220395
for dimension in range(num_dims):
for class_index in range(num_classes):
if class_index == y[training_example_index]:
dW[dimension,class_index] += X[training_example_index, dimension] * (softmax_scores[class_index] - 1)
else:
dW[dimension, class_index] += X[training_example_index, dimension] * softmax_scores[class_index]
# Average loss & add regularization
loss /= num_train
loss += reg * np.sum(W*W)
# Average gradient & add regularization
dW /= num_train
dW += 2 * reg * W
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return loss, dW
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)*****
num_train = X.shape[0]
raw_scores = X.dot(W)
raw_scores -= np.max(raw_scores)
softmax_scores = np.exp(raw_scores) / np.sum(np.exp(raw_scores), axis = 1, keepdims=True)
loss = np.sum(-np.log(softmax_scores[range(num_train), y]))
loss /= num_train
loss += reg * np.sum(W*W)
dscores = softmax_scores
dscores[range(num_train), y] -= 1
dW = np.dot(X.T, dscores)
dW /= num_train
dW += 2 * reg * W
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return loss, dW