Implement one L2-penalized Newton step for logistic regression in NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement one Newton-Raphson update on the L2-penalized mean log-loss for logistic regression, from scratch with NumPy (no sklearn). `X` is `(n_samples, d)` with the first column already ones, so the intercept is `w[0]` and is not penalized. `y` is float 0.0/1.0. The objective is:
```python
J(w) = -mean(y*log(p) + (1-y)*log(1-p)) + (lam/2)*np.sum(w[1:]**2)
```
Write it as `l2_newton_step(X, y, w, lam)`, following these requirements:
- Penalty mask `d_pen = np.ones(d); d_pen[0] = 0.0` and `p = 1/(1+np.exp(-(X @ w)))`.
- `g = X.T @ (p - y) / n_samples + lam * (d_pen * w)`.
- `H = (X.T * (p*(1-p))) @ X / n_samples + lam * np.diag(d_pen)` (adds `lam` to every diagonal entry except `H[0,0]`, nothing off-diagonal).
- Return `w - np.linalg.solve(H, g)`, an `np.ndarray` of shape `(d,)`: full step, no damping or line search, no `np.linalg.inv`.
Do not add a bias term yourself: the ones column is already in `X`.
```hint Check the shapes
`X.T` has shape `(d, n_samples)`. Work out what multiplying it elementwise by a length-`n_samples` vector does before you multiply the result by `X`.
```
```hint Where the penalty lands
Differentiate `(lam/2) * w_j**2` once for the gradient and twice for the Hessian, then ask which entries of `g` and `H` pick up each result.
```
### What a Strong Answer Covers
- A gradient and Hessian that match the objective, with the mean over samples on the log-loss terms and the penalty applied only to `w[1:]`.
- How the per-sample weights `p*(1-p)` enter the Hessian without building an `n_samples` by `n_samples` diagonal matrix.
- How the step is computed from `H` and `g` without an explicit inverse, and why that matters numerically.
- The time and memory cost of one step in terms of `n_samples` and `d`.
- Numerical edge cases: overflow in `np.exp`, near-separation, and when `H` can become singular.
### Follow-up Questions
- Why exclude the intercept from the L2 penalty?
- How does the Newton step behave when features are perfectly separable?
- When would you prefer L-BFGS or IRLS over an explicit Newton step here?
Overview: Implement a single Newton-Raphson update for L2-regularized logistic regression in NumPy, keeping the intercept out of the penalty. It tests deriving the penalized gradient and Hessian, solving the linear system stably, and reasoning about separation and Hessian conditioning.