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

125. 使用 hinge loss subgradient descent 训练线性 SVM

MediumSupervised models

线性 SVM 寻找具有最大 margin 的边界。由于 hinge loss 在 margin 为 1 时不可微,因此你需要使用 subgradient 进行训练,这与 ReLU 网络处理其转折点的方式相同。

编写 svm_train(X, y, lam, lr, steps)。X 的 shape 为 (n, d),标签 y 为 -1 或 +1。最小化 (lam / 2) * ||w||^2 + mean(max(0, 1 - y_i * (w @ x_i + b)))。bias b 不进行正则化。

从 w = 0, b = 0 开始,并精确运行 steps 次 full-batch 更新。当一个点的 margin y_i * (w @ x_i + b) < 1 时,该点为 active(恰好等于 1 则不是 active)。Subgradients 为:
- grad_w = (lam * w - sum over active i of y_i * x_i) / n
- grad_b = (- sum over active i of y_i) / n
更新 w -= lr * grad_w 和 b -= lr * grad_b。

返回 (w, b),其中 w 是一个 NumPy array,b 是一个 float。

函数def svm_train(X, y, lam, lr, steps)

示例 1

输入: X = [[2.0, 0.0], [-1.0, 0.0]], y = [1, -1], lam = 0.1, lr = 0.5, steps = 2

输出: ([0.9625, 0.0], -0.25)

约束条件

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

Only points with margin strictly less than 1 push on w and b, and every step also shrinks w a bit through the regulariser.

提示 2

Each step, compute all margins y * (X @ w + b), make a boolean mask of active points, build grad_w and grad_b from the active rows only, and update both with lr.

提示 3

Divide the active sums by the full n, not the number of active points: for example gw = lam * w - (y[a][:, None] * X[a]).sum(axis=0) / n, and b gets no lam term.

常见错误
  • 像错误版本那样在 gradient 中加上 lam * b,会使边界向原点偏移。
理解思路

线性 SVM 寻找具有最宽安全 margin 的边界。对于安全位于右侧的点(margin 至少为 1),hinge loss max(0, 1 - y x score) 为零,否则线性增长。它在 margin 为 1 处有一个转折点,因此你使用 subgradient:只有 active points(即 margin 小于 1 的点)会产生贡献。惩罚项 lam / 2 x |w|^2 使 w 保持较小,从而扩大 margin;bias 不受惩罚。

Worked example

X = [[1], [-1]], y = [1, -1], lam = 0.1, lr = 0.5, start w = 0, b = 0. 两个 margins 均为 0,因此两者都是 active。grad_w = 0.1 x 0 - (1 x 1 + (-1)(-1)) / 2 = -1; grad_b = -(1 - 1) / 2 = 0. New w = 0.5. Step 2: margins 0.5, 仍为 active; grad_w = 0.05 - 1 = -0.95; w = 0.5 + 0.475 = 0.975.

active if y_i (w . x_i + b) < 1; grad_w = lam w - sum_active y_i x_i / n; grad_b = - sum_active y_i / n. 在深度学习出现之前,SVM 是主流的分类器。
主题
Supervised models
相似题目
  • 使用 Gini impurity 寻找最佳决策树分裂点Medium
  • 使用距离加权 k 最近邻进行预测Medium
  • 运行一轮平方误差的 gradient boostingMedium
  • 使用 multinomial Naive Bayes 对词频向量进行分类Medium
所有 Supervised models 道题目
反馈
125 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def svm_train(X, y, lam, lr, steps):
# your code here
pass
​

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

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