题
在 CS231 Computing the Analytic Gradient with Backpropagation这是首先实现一个 Softmax 分类器,来自(softmax + log loss)的梯度除以批量大小(在训练中前向成本计算和反向传播循环中使用的数据数量)。
请帮我理解为什么它需要除以批量大小。
获得梯度的链式法则应该在下面。我应该在哪里合并这个部门?
代码
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D)) # data matrix (each row = single example)
y = np.zeros(N*K, dtype='uint8') # class labels
#Train a Linear Classifier
# initialize parameters randomly
W = 0.01 * np.random.randn(D,K)
b = np.zeros((1,K))
# some hyperparameters
step_size = 1e-0
reg = 1e-3 # regularization strength
# gradient descent loop
num_examples = X.shape[0]
for i in range(200):
# evaluate class scores, [N x K]
scores = np.dot(X, W) + b
# compute the class probabilities
exp_scores = np.exp(scores)
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]
# compute the loss: average cross-entropy loss and regularization
correct_logprobs = -np.log(probs[range(num_examples),y])
data_loss = np.sum(correct_logprobs)/num_examples
reg_loss = 0.5*reg*np.sum(W*W)
loss = data_loss + reg_loss
if i % 10 == 0:
print "iteration %d: loss %f" % (i, loss)
# compute the gradient on scores
dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples # <---------------------- Why?
# backpropate the gradient to the parameters (W,b)
dW = np.dot(X.T, dscores)
db = np.sum(dscores, axis=0, keepdims=True)
dW += reg*W # regularization gradient
# perform a parameter update
W += -step_size * dW
b += -step_size * db
最佳答案
这是因为您正在平均梯度而不是直接取所有梯度的总和。
你当然不能按那个大小进行划分,但这种划分有很多优点。主要原因是它是一种正则化(以避免过度拟合)。对于较小的梯度,权重不能不成比例地增长。
并且这种标准化允许在不同实验中比较不同批次大小的配置(如果两个批次的性能取决于批次大小,我如何比较它们?)
如果您除以该大小的梯度总和,则使用更高的学习率以加快训练速度可能会很有用。
This answer in the crossvalidated community非常有用。
关于python - 为什么softmax分类器梯度除以批量大小(CS231n)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65275522/