1.完成文件cs231n/classifiers/softmax.py中的softmax_loss_naive方法
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! #
#############################################################################
num_train=X.shape[0]
num_classes=W.shape[1]
loss=0.0
for i in range(num_train):
f_i=X[i].dot(W)
f_i-=np.max(f_i)
sum_j=np.sum(np.exp(f_i))
p=lambda k:np.exp(f_i[k])/sum_j
loss+=-np.log(p(y[i]))
for k in range(num_classes):
p_k=p(k)
dW[:,k]+=(p_k-(k==y[i]))*X[i]
loss/=num_train
loss+=0.5*reg*np.sum(W*W)
dW/=num_train
dW+=reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
2.完成向量版的Softmax损失函数,即softmax_loss_vectorized方法
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! #
#############################################################################
num_train=X.shape[0]
f=X.dot(W)
f-=np.max(f,axis=1,keepdims=True)
sum_f=np.sum(np.exp(f),axis=1,keepdims=True)
p=np.exp(f)/sum_f
loss=np.sum(-np.log(p[np.arange(num_train),y]))
ind=np.zeros_like(p)
ind[np.arange(num_train),y]=1
dW=X.T.dot(p-ind)
loss/=num_train
loss+=0.5*reg*np.sum(W*W)
dW/=num_train
dW+=reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
3. 超参数调优
from cs231n.classifiers import Softmax
results = {}
best_val = -1
best_softmax = None
learning_rates = [1e-7, 5e-7]
regularization_strengths = [2.5e4, 5e4]
################################################################################
# TODO: #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save #
# the best trained softmax classifer in best_softmax. #
################################################################################
iters=100
for lr in learning_rates:
for rs in regularization_strengths:
softmax=Softmax()
softmax.train(X_train,y_train,learning_rate=lr,reg=rs,num_iters=iters)
y_train_pred=softmax.predict(X_train)
acc_train=np.mean(y_train_pred==y_train)
y_val_pred=softmax.predict(X_val)
acc_val=np.mean(y_val==y_val_pred)
results[(lr,rs)]=(acc_train,acc_val)
if best_val<acc_val:
best_val=acc_val
best_softmax=softmax
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)