115. Train L2-regularised logistic regression with Newton's method
Why it matters Newton and IRLS solvers fit logistic regression in statistics packages and credit scorecards, and L2 is what keeps separable data from sending weights to infinity.
Newton's method (also called IRLS for logistic regression) uses curvature and converges in a handful of steps on small problems.
Write logreg_l2_newton(X, y, lam, n_iter). X is (n, d), y is 0/1 of length n. Minimise L = mean(-y log p - (1 - y) log(1 - p)) + (lam / 2) * ||w||^2 where p = sigmoid(b + X w). The intercept b is NOT penalised. Start from w = 0, b = 0 and take n_iter full Newton steps on theta = [b, w]: gradient g = A^T (p - y) / n + lam * pen * theta and Hessian H = A^T diag(p (1 - p)) A / n + lam * diag(pen), where A = [1, X] and pen = [0, 1, ..., 1]. Update theta -= solve(H, g). Return (w, b) with w a float array and b a float.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def logreg_l2_newton(X, y, lam, n_iter)Example 1
Input: X [[0], [1], [2], [3]], y [0, 0, 1, 1], lam 0.1, n_iter 10
Output: w [1.507653] and b -2.261511
Example 2
Input: X = [[10], [11], [12], [13], [14]], y = [0, 0, 1, 0, 1], lam = 0.05, n_iter = 15
Output: ([0.900048], -11.358366)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Prepend a column of ones, and zero out the penalty for that column.
Hint 2
p * (1 - p) are the IRLS weights.
Hint 3
(A * w8[:, None]).T @ A builds A^T diag(w8) A without a big diagonal matrix.
Hint 4
pen = [0, 1, ..., 1] keeps the intercept unpenalised.
Common mistakes
- Penalising the intercept.
- Using a sum loss in the gradient but a mean loss in the Hessian.
- Inverting H explicitly instead of solving.
Understand the idea
Gradient descent walks downhill with a fixed step. Newton's method also looks at how curved the hill is and jumps straight to the bottom of the local bowl. For logistic regression the bowl is convex, so a few Newton steps are enough.
The gradient is A^T (p - y) / n: how wrong each prediction is, pushed back onto the features. The curvature (Hessian) is A^T diag(p (1 - p)) A / n: points with p near 0.5 are uncertain and count most. L2 adds lam * w to the gradient and lam to the diagonal of the Hessian, but not for the bias, since shifting all scores up or down should be free.
Tiny example at the start: w = b = 0, so every p = 0.5 and every weight p (1 - p) = 0.25. For X = 0, 1, 2, 3 and y = 0, 0, 1, 1 the gradient for w is (0 * 0.5 + 1 * 0.5 - 2 * 0.5 - 3 * 0.5) / 4 = -0.5, telling us w should grow.
theta_new = theta - H^-1 g
Statistics packages fit logistic regression this way (IRLS).
Shapes and data flow
A (n, d + 1), p (n,), g (d + 1,), H (d + 1, d + 1)