1
我現在正在學習stanford cs231n課程。當完成softmax_loss函數時,我發現寫入全矢量化類型並不容易,尤其是處理術語。以下是我的代碼。有人可以優化代碼。將不勝感激。softmax_loss函數:將循環轉換爲矩陣運算
def softmax_loss_vectorized(W, X, y, reg):
loss = 0.0
dW = np.zeros_like(W)
num_train = X.shape[0]
num_classes = W.shape[1]
scores = X.dot(W)
scores -= np.max(scores, axis = 1)[:, np.newaxis]
exp_scores = np.exp(scores)
sum_exp_scores = np.sum(exp_scores, axis = 1)
correct_class_score = scores[range(num_train), y]
loss = np.sum(np.log(sum_exp_scores)) - np.sum(correct_class_score)
exp_scores = exp_scores/sum_exp_scores[:,np.newaxis]
# **maybe here can be rewroten into matrix operations**
for i in xrange(num_train):
dW += exp_scores[i] * X[i][:,np.newaxis]
dW[:, y[i]] -= X[i]
loss /= num_train
loss += 0.5 * reg * np.sum(W*W)
dW /= num_train
dW += reg * W
return loss, dW
感謝您的回答和建議!我仍然根據你的建議瞭解它。 – luoshao23