BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Regression15 of 18 in topic

115. Train L2-regularised logistic regression with Newton's method

HardRegression Pro

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.

Functiondef 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)
Topics
Regression
Similar questions
  • Fit Lasso with coordinate descent and soft thresholdingHard
  • Fit Poisson regression with Newton stepsHard
  • Compute the Bayesian linear regression posteriorHard
  • Fit elastic net with an intercept by coordinate descentHard
All Regression problems
Report
115 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def logreg_l2_newton(X, y, lam, n_iter):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS