Implement Full-Batch Gradient Descent for Logistic Regression
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `fit_logistic_gd(X, y, lr, n_iters)` from scratch (no `sklearn`): full-batch gradient descent for binary logistic regression with the sigmoid `1 / (1 + np.exp(-z))` (numerical guarding is optional). Return exactly the tuple `(w, b)`: `w` an `np.ndarray` of shape `(n_features,)`, `b` a Python float.
The implementation must follow these rules:
- Initialize `w = np.zeros(n_features)` and `b = 0.0` (no random initialization).
- `X` has no ones column: the intercept is the separate scalar `b`.
- Use the mean gradients `grad_w = X.T @ (p - y) / n_samples` and `grad_b = np.sum(p - y) / n_samples`, both at the current `(w, b)`, applied simultaneously.
- Run exactly `n_iters` iterations with a fixed `lr` (no early stopping, no decay).
- No regularization.
One iteration looks like this:
```python
p = sigmoid(X @ w + b) # predictions at current (w, b)
grad_w = X.T @ (p - y) / n # mean gradient, shape (n_features,)
grad_b = np.sum(p - y) / n # mean gradient, scalar
w -= lr * grad_w
b -= lr * grad_b
# repeat exactly n_iters times, then return (w, b)
```
```hint Shapes
Write down the shape of every intermediate value. `X @ w + b` and `p - y` have length `n_samples`, while `X.T @ (p - y)` must come out with length `n_features`.
```
### Constraints & Assumptions
- `X` has shape `(n_samples, n_features)`.
- `y` is a float array of `0.0`/`1.0` labels with shape `(n_samples,)`.
- NumPy is available. `sklearn` and other model-fitting libraries are not.
### What a Strong Answer Covers
- A loop that starts from the zero initialization and runs exactly `n_iters` fixed-step updates, with the intercept kept as a separate scalar.
- Correct mean gradients of the log-loss, computed from one set of predictions and applied to `w` and `b` together.
- Return values that match the contract: `w` with shape `(n_features,)` and `b` as a Python float.
- How the sigmoid behaves for logits of large magnitude, and how to keep it from overflowing.
- Time and space complexity of the loop.
### Follow-up Questions
- Why use the mean gradient (`/ n_samples`) instead of the summed gradient?
- How would you guard `sigmoid` against overflow for large negative `z`?
- How would you extend this to add L2 regularization?
Overview: Implement binary logistic regression from scratch in NumPy using full-batch gradient descent with zero initialization, a fixed learning rate and an exact number of iterations. It tests whether you can vectorize the log-loss gradients, update the weights and intercept together, and keep the sigmoid numerically stable.