Compute the Logistic Regression Log-Loss Gradient From Scratch
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `logistic_gradient(X, y, w, b)` from scratch, without `sklearn`. It returns the gradient of the mean binary log loss at the given parameters as the tuple `(grad_w, grad_b)`. Compute `z = X @ w + b` and `p = 1 / (1 + np.exp(-z))`. This is a single evaluation, not a training loop.
Requirements:
- `X` has shape `(n_samples, n_features)` with no column of ones, `b` is a separate scalar, and `y` is a float array of shape `(n_samples,)` holding `0.0` and `1.0`.
- `grad_w = X.T @ (p - y) / n_samples`, with shape `(n_features,)`.
- `grad_b = np.sum(p - y) / n_samples`, a Python or NumPy float.
- Use the mean convention (divide by `n_samples`, do not sum) and no regularization.
```python
X = np.array([[1.0, 2.0], [3.0, 4.0]])
y = np.array([0.0, 1.0])
w = np.array([0.0, 0.0])
b = 0.0
# z = [0, 0], p = [0.5, 0.5]
grad_w, grad_b = logistic_gradient(X, y, w, b)
# grad_w == [-0.5, -0.5], grad_b == 0.0
```
With all parameters at zero every probability is 0.5, so the residual `p - y` is `[0.5, -0.5]`.
```hint Check the example by hand
Work out each sample's contribution to `grad_w` separately, add them, and divide by `n_samples`. Your vectorized code should give the same numbers.
```
### Constraints & Assumptions
- `X` is `(n_samples, n_features)` and contains no intercept column; `b` is passed separately.
- `y` is a float array of `0.0` and `1.0` values with shape `(n_samples,)`.
- `n_samples >= 1` and all shapes are consistent.
### What a Strong Answer Covers
- Computes the residual `p - y` once and uses it for both gradients.
- Divides both gradients by `n_samples` and adds no regularization term.
- Returns `grad_w` with shape `(n_features,)` and a scalar `grad_b`, using vectorized NumPy with no loop over samples.
- Explains why the derivative of the log loss with respect to `z` reduces to `p - y`.
### Follow-up Questions
- Why does the gradient with respect to `z` simplify to `p - y`?
- How would you check this gradient numerically?
- How do the two gradients change if you add an L2 penalty on `w`?
- What happens in this code when `z` is very large in magnitude?
Overview: Implement the gradient of the mean binary log loss for logistic regression in NumPy, returning separate weight and bias gradients for a single evaluation. It tests the sigmoid and cross-entropy derivative, vectorized matrix math, and careful handling of array shapes and the mean convention.