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)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. Worked example: 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). Rule: 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.