Logistic Regression Hessian From Scratch

Quick Overview

Compute the Hessian of the mean binary log-loss for logistic regression in NumPy, without scikit-learn, from a design matrix that already has an intercept column. Tests the second-derivative derivation, why the labels drop out, and memory-efficient weighted matrix products.

Logistic Regression Hessian From Scratch

Role: Data Scientist

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `def logistic_hessian(X: np.ndarray, w: np.ndarray) -> np.ndarray` without `sklearn`. It returns the Hessian of the mean log-loss for binary logistic regression, $$L(w) = -\frac{1}{n} \sum_{i=1}^{n} \left[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \right], \qquad p_i = \sigma(x_i^\top w).$$ `X` has shape `(n_samples, d)` and its first column is already all ones, so do not prepend an intercept column. `w` has shape `(d,)` with the intercept at `w[0]`. Return an `np.ndarray` of shape `(d, d)`. Requirements: - `p = 1 / (1 + np.exp(-(X @ w)))` and `s = p * (1 - p)`. - Return `H = X.T @ np.diag(s) @ X / n_samples` (the mean convention). - `H` must not depend on `y`. Example: ```python X = np.array([[1., 0.], [1., 1.], [1., 2.]]) w = np.array([0., 0.]) # p = 0.5 for all rows, s = 0.25 logistic_hessian(X, w) # array([[0.25 , 0.25 ], # [0.25 , 0.4166...]]) ``` ```hint Where the labels go Start from the gradient of the mean log-loss, $\frac{1}{n} X^\top (p - y)$, and differentiate it once more with respect to $w$. Check which terms survive. ``` ```hint Size of the diagonal Work out how much memory `np.diag(s)` takes when `n_samples` is one million. Then look for a way to apply one weight per row of `X` without building that matrix. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, d)` with a leading column of ones. `w` has shape `(d,)`. - Only NumPy is allowed. No `sklearn`. - Use the mean convention: divide by `n_samples`. ### What a Strong Answer Covers - Why the Hessian of the mean log-loss is $X^\top S X / n$ with $S = \operatorname{diag}(p(1-p))$, and why `y` drops out. - Applying the per-sample weights without materializing the n by n diagonal matrix. - The time and memory cost of the computation, compared with the dense `np.diag(s)` version. - How the sigmoid and `s` behave numerically for large-magnitude logits. - A check of the result on the example, including that `H` is symmetric. ### Follow-up Questions - Why is the logistic Hessian always positive semidefinite? - How would you add L2 regularization to the Hessian? - When would you avoid forming the full Hessian, and what would you do instead?

Overview: Compute the Hessian of the mean binary log-loss for logistic regression in NumPy, without scikit-learn, from a design matrix that already has an intercept column. Tests the second-derivative derivation, why the labels drop out, and memory-efficient weighted matrix products.

General logo
General
Nov 24, 2026
mediumData ScientistOtherMachine Learning
0
0

Implement def logistic_hessian(X: np.ndarray, w: np.ndarray) -> np.ndarray without sklearn. It returns the Hessian of the mean log-loss for binary logistic regression,

L(w)=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)],pi=σ(xi⊤w).L(w) = -\frac{1}{n} \sum_{i=1}^{n} \left[ y_i \log p_i + (1 - y_i) \log(1 - p_i) \right], \qquad p_i = \sigma(x_i^\top w).

X has shape (n_samples, d) and its first column is already all ones, so do not prepend an intercept column. w has shape (d,) with the intercept at w[0]. Return an np.ndarray of shape (d, d).

Requirements:

  • p = 1 / (1 + np.exp(-(X @ w))) and s = p * (1 - p) .
  • Return H = X.T @ np.diag(s) @ X / n_samples (the mean convention).
  • H must not depend on y .

Example:

X = np.array([[1., 0.], [1., 1.], [1., 2.]])
w = np.array([0., 0.])          # p = 0.5 for all rows, s = 0.25
logistic_hessian(X, w)
# array([[0.25 , 0.25 ],
#        [0.25 , 0.4166...]])

Constraints & Assumptions

  • X has shape (n_samples, d) with a leading column of ones. w has shape (d,) .
  • Only NumPy is allowed. No sklearn .
  • Use the mean convention: divide by n_samples .

What a Strong Answer Covers Guidance

  • Why the Hessian of the mean log-loss is X⊤SX/nX^\top S X / n with S=diag⁡(p(1−p))S = \operatorname{diag}(p(1-p)) , and why y drops out.
  • Applying the per-sample weights without materializing the n by n diagonal matrix.
  • The time and memory cost of the computation, compared with the dense np.diag(s) version.
  • How the sigmoid and s behave numerically for large-magnitude logits.
  • A check of the result on the example, including that H is symmetric.

Follow-up Questions Guidance

  • Why is the logistic Hessian always positive semidefinite?
  • How would you add L2 regularization to the Hessian?
  • When would you avoid forming the full Hessian, and what would you do instead?