Compute the Hessian of the logistic regression loss
Newton's method and influence functions need second derivatives. For logistic regression the Hessian has a clean form.
Write logistic_hessian(X, w). With p = sigmoid(X @ w) and the mean log loss over n rows, return the (d, d) Hessian X.T diag(p (1 - p)) X / n. Do not build the n by n diagonal matrix.
def logistic_hessian(X, w)Example
X = [[1, 0], [0, 1]], w = [0, 0] gives [[0.125, 0], [0, 0.125]].
Understand the idea
The Hessian of a loss is the matrix of second derivatives: it says how curved the loss is in each direction. For logistic regression it has a neat form: each row contributes its outer product x x^T, weighted by p * (1 - p), the slope of the sigmoid at that row. Rows the model is already sure about (p near 0 or 1) add almost no curvature. Worked example: X = [[1, 1], [1, -1]], w = [0, 0]. Then p = 0.5 for both rows, weight 0.25. Outer products: [[1, 1], [1, 1]] and [[1, -1], [-1, 1]], sum [[2, 0], [0, 2]]. H = 0.25 * [[2, 0], [0, 2]] / 2 = [[0.25, 0], [0, 0.25]]. Rule: p = sigmoid(X w); H = X^T diag(p (1 - p)) X / n. Do not build the n by n diagonal matrix; instead scale each row of X by its weight and multiply by X^T. Using p alone instead of p (1 - p) gives the wrong curvature. Used in Newton's method for logistic regression and in influence function analysis.