Train L2-regularised logistic regression with Newton's method

HardRegressionPro

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.

Signaturedef logreg_l2_newton(X, y, lam, n_iter)

Example

X [[0], [1], [2], [3]], y [0, 0, 1, 1], lam 0.1, n_iter 10 gives w [1.507653] and b -2.261511.

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.

Rule: 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)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplelogreg_l2_newton([[0], [1], [2], [3]], [0, 0, 1, 1], 0.1, 10)
  • Sample 2: shifted data needs biaslogreg_l2_newton([[10], [11], [12], [13], [14]], [0, 0, 1, 0, 1], 0.05, 15)