Gradient Check for Logistic Regression
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `gradient_check(X, y, w, eps)` from scratch, using NumPy only (no scikit-learn or SciPy). It compares the analytic gradient of the logistic loss with a finite-difference estimate. The objective is
`J(v) = -np.mean(y*np.log(q) + (1-y)*np.log(1-q))` with `q = 1/(1+np.exp(-(X @ v)))`.
Requirements:
- The analytic gradient is `g = X.T @ (p - y) / n_samples`, where `p` is the sigmoid of `X @ w`.
- The numeric gradient uses the central difference for each `j` in `range(d)`: `num[j] = (J(w + eps*e_j) - J(w - eps*e_j)) / (2*eps)`. A one-sided difference does not meet the spec.
- Perturb a copy of `w`. Never mutate `w` in place.
- Return `(num, max_abs_diff)`, where `num` has shape `(d,)` and `max_abs_diff = float(np.max(np.abs(g - num)))`.
- There is no regularization term.
Example:
```python
X = np.array([[1.0, 0.5], [1.0, -1.2], [1.0, 2.0]])
y = np.array([1.0, 0.0, 1.0])
w = np.array([0.1, -0.3])
num, max_abs_diff = gradient_check(X, y, w, eps=1e-5)
# num.shape == (2,)
# max_abs_diff is tiny (e.g. < 1e-7) when the analytic gradient is correct
```
```hint Write the loss once
Write `J(v)` as a helper that takes any weight vector, and call it on both perturbed vectors for each coordinate.
```
```hint Watch the copies
Check what `w` looks like after the loop if you add `eps` to `w[j]` directly, or if you write `w_plus = w` without `.copy()`.
```
### Constraints & Assumptions
- `X` has shape `(n_samples, d)`, and its first column is already all ones (the intercept).
- `w` has shape `(d,)`.
- `y` has shape `(n_samples,)` and holds the floats 0.0 and 1.0.
- `eps` is a small positive float such as `1e-5`, and all arithmetic is in float64.
### What a Strong Answer Covers
- Implements `J` exactly as specified and evaluates it on two perturbed copies of `w` for each coordinate.
- Computes the analytic gradient as given and returns `num` and `max_abs_diff` with the required shape and type.
- Leaves the caller's `w` unchanged.
- Explains why the central difference is more accurate than a one-sided difference.
- States the cost: two loss evaluations per coordinate, ${O(n d^2)}$ in total.
### Follow-up Questions
- How do you pick a good `eps`?
- Why compare relative error instead of the raw `max_abs_diff`?
- How would this extend to regularized logistic regression?
Overview: Implement a NumPy gradient check that compares the analytic gradient of logistic regression's mean log loss with a central finite-difference estimate. It tests the log-loss gradient, finite-difference accuracy, choosing the step size, and avoiding in-place changes to the weight vector.