BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Calculus and gradients6 of 14 in topic

43. 推导 softmax 加上 cross-entropy 的梯度

MediumCalculus and gradients
提问于ByteDanceGoogle

几乎所有分类器和语言模型的最后一层都是 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)
Play with it

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.

Sweep the logit of
0%25%50%75%100%-4-2024logit of class 0probability0%25%50%75%100%probabilityclass 054.7%class 133.1%class 212.2%
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 和其他所有框架为了速度和稳定性都硬编码了这个融合梯度。

主题
Calculus and gradients
公司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)

来自公开面试报告和指南。与这些公司无隶属关系或背书关系。

相似题目
  • 推导余弦相似度对单个向量的梯度Medium
  • 计算逻辑回归损失的 Hessian 矩阵Medium
  • 使用 Armijo 回溯线性搜索选择步长Medium
  • 对均值和 log sigma 求高斯负对数似然的导数Medium
所有 Calculus and gradients 道题目
反馈
43 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def softmax_ce_grad(logits, labels):
# your code here
pass
​
softmax_ce_grad(_z, _y)[0]

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 8 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS