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

45. 计算逻辑回归损失的 Hessian 矩阵

MediumCalculus and gradients

Newton's method 和 influence functions 需要二阶导数。对于逻辑回归,Hessian 矩阵有一个简洁的形式。

编写 logistic_hessian(X, w)。设 p = sigmoid(X @ w) 且为 n 行的平均 log loss,返回 (d, d) 的 Hessian X.T diag(p (1 - p)) X / n。不要构建 n by n 的对角矩阵。

函数def logistic_hessian(X, w)

示例 1

输入: X = [[1, 0], [0, 1]], w = [0, 0]

输出: [[0.125, 0], [0, 0.125]]

约束条件

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

The diagonal matrix only scales each row of X, so you can apply it with broadcasting instead of building it.

提示 2

Compute p = sigmoid(X @ w), then the weights s = p * (1 - p), scale each row of X by its weight, multiply by X with a transpose, and divide by n.

提示 3

Use s[:, None] so the (n,) weights broadcast across the d columns: (X * s[:, None]).T @ X gives the (d, d) result before dividing by X.shape[0].

理解思路

损失函数的 Hessian 是二阶导数矩阵:它表示损失函数在每个方向上的曲率。对于逻辑回归,它有一个整洁的形式:每一行通过其外积 x x^T 做出贡献,并由 p * (1 - p)(即该行 sigmoid 的斜率)进行加权。模型已经确定的行(p 接近 0 或 1)几乎不增加曲率。

Worked example

X = [[1, 1], [1, -1]], w = [0, 0]。则两行的 p = 0.5,权重为 0.25。外积分别为: [[1, 1], [1, 1]] 和 [[1, -1], [-1, 1]],求和得 [[2, 0], [0, 2]]。H = 0.25 * [[2, 0], [0, 2]] / 2 = [[0.25, 0], [0, 0.25]]。

p = sigmoid(X w); H = X^T diag(p (1 - p)) X / n。不要构建 n by n 的对角矩阵;相反,应按权重缩放 X 的每一行,然后乘以 X.T。仅使用 p 而不是 p (1 - p) 会导致曲率计算错误。该方法用于逻辑回归的 Newton's method 和 influence function 分析。
主题
Calculus and gradients
相似题目
  • 推导 softmax 加上 cross-entropy 的梯度Medium
  • 推导余弦相似度对单个向量的梯度Medium
  • 使用 Armijo 回溯线性搜索选择步长Medium
  • 对均值和 log sigma 求高斯负对数似然的导数Medium
所有 Calculus and gradients 道题目
反馈
45 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def logistic_hessian(X, w):
# your code here
pass
​

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

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