def svm_loss_vectorized(W, X, y, reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
num_train = X.shape[0]
loss = 0.0
dW = np.zeros(W.shape) # initialize the gradient as zero
#############################################################################
# TODO: #
# Implement a vectorized version of the structured SVM loss, storing the #
# result in loss. #
#############################################################################
scores = X.dot(W)
margin = np.maximum(0, scores + 1 - scores[xrange(num_train), y][:,np.newaxis])
margin[xrange(num_train), y] = 0
# hinge[hinge<0] = 0
loss = np.sum(margin)
loss /= num_train
loss += 0.5*reg*np.sum(W*W)
#############################################################################
# END OF YOUR CODE #
#############################################################################
margin[margin>0] = 1.0
margin[xrange(num_train), y] -= np.sum(margin, axis=1)
dW = X.T.dot(margin)/num_train + reg*W
#############################################################################
# TODO: #
# Implement a vectorized version of the gradient for the structured SVM #
# loss, storing the result in dW. #
# #
# Hint: Instead of computing the gradient from scratch, it may be easier #
# to reuse some of the intermediate values that you used to compute the #
# loss. #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
评论列表
文章目录