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

229. 基于原始 logits 的 label smoothing 交叉熵

EasyLosses
提问于DeepMindOpenAI

Label smoothing 可以防止分类器将其 logits 推向极端值。将 one-hot 目标与均匀分布混合,因此模型永远不会被要求给出概率恰好为 1 的结果。

编写 label_smoothed_ce(logits, targets, eps),其中 logits 的形状为 (n, C),targets 是一个长度为 n 的类别 ID 列表,且 0 <= eps < 1。
- 第 i 行的平滑目标为 q = (1 - eps) * one_hot(targets[i]) + eps / C,应用于每个类别(包括真实类别)。
- 该行的 Loss 为 -sum_c q[c] * log_softmax(logits[i])[c]。
- 返回所有行的平均值,类型为 float。
使用稳定的 log-softmax 以确保像 1000 这样的 logits 也能正常工作。

函数def label_smoothed_ce(logits, targets, eps)

示例 1

输入: logits [[0, 0]], targets [0], eps 0.2

输出: log 2 = 0.693147..

解析: Because the prediction is already uniform.

示例 2

输入: logits = [[1000.0, 0.0, -1000.0]], targets = [0], eps = 0.3

输出: 300

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
提示 1

log_softmax = z - max(z) - log(sum(exp(z - max(z)))).

提示 2

使用 np.full((n, C), eps / C) 构建 q,并在目标列加上 1 - eps。

常见错误
  • 有 Bug 的版本将 eps / (C - 1) 分散到了错误的类别上,并在真实类别上恰好放置了 1 - eps。
理解思路

Label smoothing 告诉模型正确答案是非常可能的,但不是绝对确定的。将 one-hot 目标与均匀分布混合,从而使模型停止将 logits 推向极端值。在本题中,eps 被分散到所有 C 个类别中,包括真实类别。

Worked example

C = 2, eps = 0.2, 真实类别为 0。q = (1 - 0.2) * [1, 0] + 0.2 / 2 = [0.9, 0.1]。Logits [2, 0]: logsumexp = log(e^2 + 1) = 2.1269,因此 log-probs 为 [-0.1269, -2.1269]。Loss = 0.9 * 0.1269 + 0.1 * 2.1269 = 0.1142 + 0.2127 = 0.3269。

q = (1 - eps) * one_hot + eps / C, row loss = -sum over classes of q times log_softmax(logits), 然后对行求平均。计算 log_softmax 时,使用 logits 减去其最大值,再减去 exp 之和的对数,这样像 1000 这样的 logits 也能保持有限值。常用于训练图像分类器和许多 transformer 模型,通常 eps = 0.1。
主题
Losses
公司2
  • DeepMind the topic appears in interview reports Google DeepMind Onsite Interview: Every Round, What It Tests (SpaceComplexity)
  • OpenAI a candidate reported this question AI interviews stopped asking 'what is a transformer'; now they hand you a broken one (Medium)

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

相似题目
  • 直接从 logits 计算二元交叉熵Easy
  • 计算 multiclass hinge lossEasy
  • 计算 soft Dice lossEasy
  • 计算正样本 anchor 的 smooth L1 box regression lossEasy
所有 Losses 道题目
反馈
229 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def label_smoothed_ce(logits, targets, eps):
# your code here
pass
​

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

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