104. Train logistic regression one gradient step at a time
Logistic regression predicts p = sigmoid(X @ w + b) and is trained by lowering the mean log loss. The gradient is surprisingly simple: the prediction error times the inputs.
Write logreg_step(X, y, w, b, lr) that does ONE gradient descent step and returns (new_w, new_b, loss) where loss is the mean log loss BEFORE the step.
grad_w = X.T @ (p - y) / n, grad_b = mean(p - y). Clip p to [1e-12, 1 - 1e-12] inside the log.
def logreg_step(X, y, w, b, lr)Example 1
Input: logreg_step([[1.0], [-1.0]], [1, 0], [0.0], 0.0, 0.5)
Output: ([0.25], 0.0, 0.6931)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
The gradient of the mean log loss is just the prediction error p - y times the inputs, averaged over the samples.
Hint 2
Compute p = 1 / (1 + np.exp(-(X @ w + b))), the mean log loss, the gradients X.T @ (p - y) / n and mean(p - y), then step against them with lr.
Hint 3
Clip p with np.clip(p, 1e-12, 1 - 1e-12) only inside the logs, use the unclipped p for the gradients, and remember the loss is measured before the update.
Common mistakes
- The buggy version flips the sign of p - y, so it climbs the loss.
Understand the idea
Logistic regression turns a linear score into a probability with the sigmoid, then learns by lowering the mean log loss. The gradient has a friendly form: the prediction error (p - y) times the inputs. Gradient descent moves weights against the gradient, like walking downhill.
one sample x = [1], y = 1, w = [0], b = 0, lr = 0.1. The score is 0, so p = sigmoid(0) = 0.5. Loss = -ln(0.5) = 0.693, measured before the update. Error p - y = -0.5. grad_w = 1 x (-0.5) / 1 = -0.5 and grad_b = -0.5. New w = 0 - 0.1 x (-0.5) = 0.05, new b = 0.05. Clip p to [1e-12, 1 - 1e-12] inside the log so it never hits log(0).
p = sigmoid(Xw + b); loss = -mean(y log p + (1 - y) log(1 - p)); grad_w = X^T (p - y) / n; grad_b = mean(p - y); subtract lr times each
Click and fraud models still use this.
Topics
Companies3
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- Microsoft the topic appears in interview reports Microsoft Interview Prep: Questions, Process & Study Plan
From public interview reports and guides. Not affiliated with or endorsed by these companies.