我想計算沒有循環的SVM的損失。但我無法做到。需要一些啓發。如何矢量化SVM中的損失
和
def svm_loss_vectorized(W, X, y, reg):
loss = 0.0
scores = np.dot(X, W)
correct_scores = scores[y]
deltas = np.ones(scores.shape)
margins = scores - correct_scores + deltas
margins[margins < 0] = 0 # max -> Boolean array indexing
margins[np.arange(scores.shape[0]), y] = 0 # Don't count j = yi
loss = np.sum(margins)
# Average
num_train = X.shape[0]
loss /= num_train
# Regularization
loss += 0.5 * reg * np.sum(W * W)
return loss
它應輸出同一損失爲以下功能。
def svm_loss_naive(W, X, y, reg):
num_classes = W.shape[1]
num_train = X.shape[0]
loss = 0.0
for i in range(num_train):
scores = X[i].dot(W)
correct_class_score = scores[y[i]]
for j in range(num_classes):
if j == y[i]:
continue
margin = scores[j] - correct_class_score + 1 # note delta = 1
if margin > 0:
loss += margin
loss /= num_train # mean
loss += 0.5 * reg * np.sum(W * W) # l2 regularization
return loss
什麼是輸入的形狀? – Divakar
W.shape =(3073,10),X.shape =(500,3073),y.shape(500,) – WeiJay