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

230. 计算 multiclass hinge loss

EasyLosses

重要性 Max-margin losses 在 reranking 和 contrastive training 中仍然被广泛使用。

SVM 风格的 multiclass loss 要求正确类别的得分要比其他所有类别的得分高出一个 margin。

编写 multiclass_hinge(S, y, margin=1.0)。S 是 (n, k) 的 scores,y 是 (n,) 的正确类别索引。对于每一行,对所有 j != y_i 的类别计算 max(0, S[i, j] - S[i, y_i] + margin) 之和,然后返回所有行的平均值。

函数def multiclass_hinge(S, y, margin=1.0)
Play with it

One hinge term of the multiclass SVM loss

Each wrong class j adds max(0, s_j − s_y + margin). The x-axis is s_j − s_y.

024-4-2024s_j − s_y
s_j − s_y
0.00
hinge term
1
slope of hinge term
1
hinge termslope

示例 1

输入: S = [[3, 1, 2.5]], y = [0]

输出: max(0, 1 - 3 + 1) + max(0, 2.5 - 3 + 1) = 0.5

示例 2

输入: S = [[1, 2, 3], [5, 0, 0]], y = [2, 0]

输出: 0.0

示例 3

输入: S = [[1, 2, 3], [5, 0, 0]], y = [2, 0], margin = 2.0

输出: 0.5

约束条件

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

使用 broadcasting 计算所有 margins,并将正确类别的项置为 0。

提示 2

使用 fancy indexing 获取正确的 scores。

提示 3

在求和之前将 j = y_i 的项置为 0。

常见错误
  • 计入了正确类别,这会导致每一行都多加了一个 margin。
理解思路

由 linear SVMs 使用的 multiclass hinge loss 要求正确类别的得分至少要比其他每个类别的得分高出一个 margin。每个过于接近的错误类别都会增加一个惩罚项,其大小等于其差值。

Worked example

margin 为 1,两行数据。Row 1: S = [2, 3, 0.5], 正确类别为 0。Class 1: 3 - 2 + 1 = 2。Class 2: 0.5 - 2 + 1 = -0.5, clipped 到 0。Row loss = 2。Row 2: S = [1, 4, 2], 正确类别为 1。Class 0: 1 - 4 + 1 = -2, clipped 到 0。Class 2: 2 - 4 + 1 = -1, clipped 到 0。Row loss = 0。Mean = (2 + 0) / 2 = 1.0。

loss_i = sum over j != y_i of max(0, S[i, j] - S[i, y_i] + margin); 返回所有行的平均值。要排除正确类别本身:如果你包含了它,它会给每一行都增加一个正好等于 margin 的值。应用场景: linear SVM 分类器,以及用于 retrieval 和 reward models 的 margin-based ranking losses。
主题
Losses
相似题目
  • 直接从 logits 计算二元交叉熵Easy
  • 基于原始 logits 的 label smoothing 交叉熵Easy
  • 计算 soft Dice lossEasy
  • 计算正样本 anchor 的 smooth L1 box regression lossEasy
所有 Losses 道题目
反馈
230 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def multiclass_hinge(S, y, margin=1.0):
# your code here
pass
​

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

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