Sub topic 9
The gradient of log loss and a NumPy implementation
This chapter assumes you know the sigmoid model and log loss from the earlier chapters. It also assumes you can take a derivative with the chain rule and write basic NumPy. You will derive the gradient of the mean log loss, turn it into vectorized code, and check the code numerically.
The setup
For one example with feature vector x, label y (0 or 1), weights w and bias b, the model computes three things in order:
- The score z = w·x + b.
- The probability p = σ(z) = 1 / (1 + e^(−z)).
- The loss ℓ = −[y log p + (1 − y) log(1 − p)].
The training objective is the mean of ℓ over n examples. To run gradient descent, you need the partial derivatives of that mean with respect to each weight and the bias.
The chain rule multiplies one derivative per arrow, working backward from the loss:
∂ℓ/∂wj = (∂ℓ/∂p) · (∂p/∂z) · (∂z/∂wj)
Deriving each factor
Loss with respect to p. Differentiate the two log terms:
∂ℓ/∂p = −y/p + (1 − y)/(1 − p)
Put both terms over a common denominator:
∂ℓ/∂p = (p − y) / (p(1 − p))
Sigmoid derivative. The sigmoid has a convenient derivative:
∂p/∂z = p(1 − p)
Score with respect to weights. Since z = Σ wj xj + b, we get ∂z/∂wj = xj and ∂z/∂b = 1.
Combine. The factor p(1 − p) appears in the denominator of the first term and in the numerator of the second, so it cancels:
∂ℓ/∂z = (p − y)
So for one example:
- ∂ℓ/∂wj = (p − y) · xj
- ∂ℓ/∂b = (p − y)
Averaging over n examples gives the batch gradient:
- ∇_w L = Xᵀ(p − y) / n
- ∂L/∂b = mean(p − y)
Here X has shape (n, d), and p and y have shape (n,).
This is the same form as the gradient of mean squared error in linear regression. The difference is that p comes from the sigmoid instead of being the raw score. The cancellation above is not an accident. Log loss is the natural loss for the sigmoid, and it keeps the gradient from shrinking when the sigmoid saturates.
Reading the gradient
The term p − y is the residual for each example. It is positive when the model overestimates the positive class and negative when it underestimates it. Its magnitude lies in (0, 1).
The product Xᵀ(p − y) sums each feature column weighted by those residuals. A weight grows when its feature tends to be large on examples the model under-predicts, and shrinks when the feature is large on examples it over-predicts. At the optimum the gradient is zero, which means the residuals are uncorrelated with every feature and sum to zero.
A NumPy implementation
The code below implements the gradient, the loss, and a numerical check. Two details matter for stability. The sigmoid is written as exp(-logaddexp(0, -z)), which avoids overflow warnings for large negative scores. The loss clips probabilities away from 0 and 1 so that log never receives zero.
import numpy as np
def sigmoid(z):
# 1 / (1 + e^-z), computed without overflow for large |z|
return np.exp(-np.logaddexp(0.0, -z))
def log_loss(X, y, w, b):
p = np.clip(sigmoid(X @ w + b), 1e-12, 1 - 1e-12)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def gradient(X, y, w, b):
n = X.shape[0]
error = sigmoid(X @ w + b) - y
return X.T @ error / n, error.mean()
def fit_logistic(X, y, lr=0.1, steps=1000):
w = np.zeros(X.shape[1])
b = 0.0
for _ in range(steps):
grad_w, grad_b = gradient(X, y, w, b)
w -= lr * grad_w
b -= lr * grad_b
return w, b
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-1, 1, (100, 2)), rng.normal(1, 1, (100, 2))])
y = np.array([0] * 100 + [1] * 100)
w, b = fit_logistic(X, y)
pred = sigmoid(X @ w + b) >= 0.5
print("loss:", log_loss(X, y, w, b))
print("accuracy:", (pred == y).mean())Each step does three things: one matrix-vector product for the scores, one subtraction for the residuals, and one more matrix-vector product for the gradient. No Python loop runs over examples or features. Both products cost O(nd), so one step costs O(nd).
Checking the gradient numerically
A derivation can be right on paper and wrong in code. A central finite difference estimates each partial derivative as (L(θ + h) − L(θ − h)) / 2h. Compare it with your analytic gradient at a random point.
def numerical_gradient(X, y, w, b, h=1e-6):
grad_w = np.zeros_like(w)
for j in range(len(w)):
w_hi, w_lo = w.copy(), w.copy()
w_hi[j] += h
w_lo[j] -= h
grad_w[j] = (log_loss(X, y, w_hi, b) - log_loss(X, y, w_lo, b)) / (2 * h)
grad_b = (log_loss(X, y, w, b + h) - log_loss(X, y, w, b - h)) / (2 * h)
return grad_w, grad_b
w0 = rng.normal(size=2)
b0 = 0.3
analytic_w, analytic_b = gradient(X, y, w0, b0)
numeric_w, numeric_b = numerical_gradient(X, y, w0, b0)
print(np.max(np.abs(analytic_w - numeric_w)), abs(analytic_b - numeric_b))Both printed numbers should be tiny, typically below 1e-8. A value near 1e-2 or larger points to a bug, such as a missing division by n or a sign error. Run this check on small data, because it needs 2d + 2 loss evaluations.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Loss rises or becomes `nan` | Learning rate too high, or unscaled features | Lower `lr`, standardize features |
| Gradient check fails by a constant factor | Forgot the division by n, or used sum in one place and mean in the other | Use the mean in both |
| Weights move the wrong way | Used `y - p` while still subtracting the gradient | Keep `p - y` with `w -= lr * grad` |
| `RuntimeWarning: overflow in exp` | Naive `1 / (1 + np.exp(-z))` with large negative z | Use the `logaddexp` form |
| `log(0)` gives `-inf` | Probability exactly 0 or 1 in the loss | Clip probabilities |
| Shape error or silent wrong result | `y` stored as a column of shape (n, 1) | Flatten it with `y.ravel()` |
What the implementation does not include
This version has no regularization. Adding an L2 penalty (λ/2)‖w‖² to the loss adds λw to the weight gradient and leaves the bias gradient unchanged. The loss is convex, so gradient descent with a small enough step size reaches the global minimum. On perfectly separable data, though, the minimum lies at infinite weights, and the weights keep growing as training continues. Later chapters return to both points.
Exercise
A single example has features x = (2, −1), label y = 1, weights w = (0, 0) and bias b = 0. What is its contribution to the gradient with respect to w and b before averaging?
Show answer
The score is z = 0, so p = σ(0) = 0.5 and the residual is p − y = 0.5 − 1 = −0.5. The weight gradient is (p − y)·x = (−0.5)(2, −1) = (−1, 0.5). The bias gradient is −0.5. A gradient step subtracts these, so w1 increases, w2 decreases, and b increases, which raises the predicted probability of the positive class for this example.
Exercise
Why does the factor p(1 − p) cancel in the log-loss gradient, and what would go wrong if you trained a sigmoid model with squared error instead?
Show answer
The derivative of log loss with respect to p has p(1 − p) in its denominator, and the derivative of the sigmoid with respect to z equals p(1 − p), so the two cancel and leave p − y. With squared error, the gradient keeps the p(1 − p) factor. When the model is confidently wrong, p is near 0 or 1, so this factor is near 0 and the gradient almost vanishes. Training then stalls exactly where the model most needs to correct itself.