One Newton-Raphson Step for Logistic Regression
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `newton_step(X, y, w)` from scratch (no `sklearn` or `statsmodels`). It performs exactly one Newton-Raphson update on the mean log-loss of binary logistic regression and returns the updated coefficients. `X` has shape `(n_samples, d)` and its first column is already all ones (do not prepend), `w` has shape `(d,)` with the intercept at `w[0]`, and `y` holds float labels 0.0 or 1.0 with shape `(n_samples,)`.
Requirements:
- `p = 1/(1+np.exp(-(X @ w)))` and `g = X.T @ (p - y) / n_samples`.
- `H = (X.T * (p * (1 - p))) @ X / n_samples`, using the same mean convention as `g`.
- Return `w - np.linalg.solve(H, g)`, an `np.ndarray` of shape `(d,)`.
- Use `np.linalg.solve(H, g)`, not `np.linalg.inv(H) @ g`.
- Take a single full step: no loop, no step size or damping, no regularization.
```hint Watch the shapes
`p * (1 - p)` has one entry per sample. Work out which axis of `X.T` it has to line up with so that `H` ends up `d` by `d`.
```
### Constraints & Assumptions
- `numpy` is imported as `np`.
- Inputs are well-formed with matching shapes: `X` is `(n_samples, d)` with a leading column of ones, `y` is `(n_samples,)`, `w` is `(d,)`.
### What a Strong Answer Covers
- Vectorized probabilities, gradient and Hessian with consistent shapes and the same `1/n_samples` convention in `g` and `H`.
- One full step computed with `np.linalg.solve` and returned as a `(d,)` array, with no loop or damping.
- Why solving the system beats inverting `H`, and why the mean convention does not change the step.
- The cost of the step and the conditions that make `H` close to singular.
### Follow-up Questions
- How would you keep the step stable when `H` is near-singular?
- How does this Newton step relate to iteratively reweighted least squares (IRLS)?
- How would you test that your gradient and Hessian are correct?
Overview: Write a NumPy function that performs a single Newton-Raphson update of logistic regression coefficients on the mean log-loss. Tests vectorizing the gradient and Hessian, keeping array shapes consistent, solving the Newton system safely, and handling an ill-conditioned Hessian.