Logistic regression with gradient descent
Problem
- (a)
logistic_loss_grad(X, y, w, b)returns the mean binary cross-entropy loss and its gradients(loss, grad_w, grad_b)forp = σ(Xw + b). It must be finite for |Xw + b| up to 1000. - (b)fit_logistic(X, y, lr, epochs)runs full-batch gradient descent fromw = 0, b = 0for exactlyepochssteps and returns(w, b).
Signature
def logistic_loss_grad(X, y, w, b) -> tuple[float, np.ndarray, float]: ... def fit_logistic(X, y, lr: float = 0.1, epochs: int = 1000) -> tuple[np.ndarray, float]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(logistic_loss_grad([[1.0],[2.0]], [0, 1], [0.0], 0.0), (0.693147, [-0.25], 0.0))
True
>>> close(logistic_loss_grad([[1.0, 0.0],[0.0, 1.0]], [1, 1], [0.0, 0.0], 0.0), (0.693147, [-0.25, -0.25], -0.5))
TrueHints
Gradient: X^T(p - y)/n for w, mean(p - y) for b.
Loss = mean(logaddexp(0, z) - y*z) with z = Xw + b — finite for |z| up to 1000.
Full-batch descent from w=0, b=0 for exactly epochs steps, fully vectorised.
Reference solution
import numpy as np
def _sigmoid(z):
return np.where(z >= 0, 1 / (1 + np.exp(-np.abs(z))), np.exp(-np.abs(z)) / (1 + np.exp(-np.abs(z))))
def logistic_loss_grad(X, y, w, b):
X = np.asarray(X, float); y = np.asarray(y, float); w = np.asarray(w, float)
z = X @ w + b
# stable BCE: log(1+e^z) - y z
loss = np.mean(np.logaddexp(0, z) - y * z)
p = _sigmoid(z)
gw = X.T @ (p - y) / len(y)
gb = float(np.mean(p - y))
return float(loss), gw, gb
def fit_logistic(X, y, lr=0.1, epochs=1000):
X = np.asarray(X, float)
w = np.zeros(X.shape[1]); b = 0.0
for _ in range(epochs):
_, gw, gb = logistic_loss_grad(X, y, w, b)
w -= lr * gw; b -= lr * gb
return w, bWhat a strong solution covers
- Correct gradient
Xᵀ(p − y)/nandmean(p − y). - Stable loss via
logaddexp(0, z) − y·z, or clipping. - Fully vectorised.
- Discusses LR choice, convergence checks, SGD vs full batch, L2 regularisation, and divergence on separable data without regularisation.
Common mistakes
- sign errors in the gradient
log(sigmoid(z))returning −inf for large negative z.