43. 推导 softmax 加上 cross-entropy 的梯度
几乎所有分类器和语言模型的最后一层都是 softmax 后面跟着 cross-entropy。它相对于 logits 的梯度有一个著名的简洁形式,并且每个框架都对其进行了硬编码。
编写 softmax_ce_grad(logits, labels),其中 logits 的 shape 为 (n, c),integer labels 的 shape 为 (n,)。返回 (loss, grad):
- loss: n 行的平均 cross-entropy。
- grad: shape 为 (n, c),该平均 loss 相对于 logits 的梯度。
确保在 logits 较大时数值稳定。
def softmax_ce_grad(logits, labels)Softmax probabilities behind the cross-entropy gradient
The gradient of cross-entropy with respect to the logits is p − y. Slide a logit and the probabilities you would subtract y from update live.
- entropy (nats)
- 0.953
- top class
- class 0
示例 1
输入: logits = [[1000.0, 0.0]], labels = [0]
输出: (-0.0, [[0.0, 0.0]])
示例 2
输入: logits = [[1000.0, 0.0]], labels = [1]
输出: (1000.0, [[1.0, -1.0]])
示例 3
输入: logits = [[0.0, 0.0]], labels = [1]
输出: (0.693147, [[0.5, -0.5]])
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 8 tests to be accepted.
提示 1
令 p = softmax(logits),则平均 loss 的梯度为 (p - one_hot(labels)) / n。
提示 2
计算 log-softmax 时使用 z - max - log(sum(exp(z - max)))。
常见错误
- 在有 bug 的版本中,忘记除以 n 就是那个 bug。
理解思路
Softmax 后面跟着 cross-entropy 是几乎所有分类器和语言模型的最后一步。它相对于 logits 的梯度非常简洁:预测概率减去 one-hot label。如果模型预测正确,推力就很小;如果预测错误,推力就很大。Worked example, 一行数据, logits [2, 0], label 0. Softmax 为 [0.881, 0.119]. Loss = -ln(0.881) = 0.127. Gradient = [0.881 - 1, 0.119 - 0] = [-0.119, 0.119]. 因为这里的 loss 是 n 行的平均值,所以每一行的梯度都要除以 n。对于较大的 logits,在进行 exp 之前减去该行的最大值,并使用 z - max - log(sum(exp)) 来计算 log-probabilities 以避免 log(0)。
loss = mean over rows of -log softmax(z)[y]; grad = (softmax(z) - onehot(y)) / n
PyTorch 和其他所有框架为了速度和稳定性都硬编码了这个融合梯度。
公司2
- ByteDance a candidate reported this question ByteDance Machine Learning Engineer Interview | Screna AI
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。