45. 计算逻辑回归损失的 Hessian 矩阵
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)几乎不增加曲率。
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 分析。