Sub topic 9
The gradient of log loss and a NumPy implementation
This chapter assumes you know Python and NumPy, can take a basic derivative, and have seen log loss as the training objective. Here you derive its gradient and turn it into a working training loop.
The setup
For one example, the model computes a score z = w·x + b, then a probability p = σ(z). The average log loss over n examples is:
L = −(1/n) Σ [ y log p + (1 − y) log(1 − p) ]
To get the gradient, apply the chain rule through three steps.
Deriving the gradient
Work with a single example and write the loss as ℓ = −[y log p + (1 − y) log(1 − p)].
- The loss with respect to the probability is ∂ℓ/∂p = −y/p + (1 − y)/(1 − p).
- The sigmoid has a convenient derivative: ∂p/∂z = p(1 − p).
- Multiply the two. The factors of p and (1 − p) cancel, which leaves ∂ℓ/∂z = p − y.
Since ∂z/∂w = x and ∂z/∂b = 1, averaging over the batch gives:
- ∂L/∂w = Xᵀ(p − y) / n
- ∂L/∂b = mean(p − y)
The result has the same form as the gradient for linear regression with squared error. Only the definition of p differs. The error p − y is the signed gap between the predicted probability and the label.
Implementation
The code below trains with batch gradient descent. It also tracks the loss and checks the analytic gradient against a finite-difference estimate.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-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):
error = sigmoid(X @ w + b) - y
return X.T @ error / len(y), error.mean()
def fit_logistic(X, y, lr=0.1, steps=1000):
w, b = np.zeros(X.shape[1]), 0.0
for step in range(steps):
grad_w, grad_b = gradient(X, y, w, b)
w -= lr * grad_w
b -= lr * grad_b
if step % 250 == 0:
print(step, log_loss(X, y, w, 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)
# Gradient check at a random point
w0, b0 = rng.normal(size=2), 0.3
h = 1e-6
step = np.array([h, 0.0])
numeric = (log_loss(X, y, w0 + step, b0) - log_loss(X, y, w0 - step, b0)) / (2 * h)
print(numeric, gradient(X, y, w0, b0)[0][0])
w, b = fit_logistic(X, y)
pred = sigmoid(X @ w + b) >= 0.5
print((pred == y).mean())The two gradient-check numbers should agree to several decimal places. The loss should fall at each printed step, and final accuracy should be roughly 0.9 because the two clusters overlap.
Common errors
- Wrong sign. The update is
w -= lr * grad. Adding the gradient climbs the loss. - Shape mix-ups.
X.T @ errorgives shape(d,). Do not average it over the wrong axis. - Forgetting to divide by
n. The effective learning rate then grows with the dataset size. - Overflow in
exp. Very large negativezcan trigger warnings. Scaling features, covered in a later chapter, usually prevents this.
Exercise
Why does the gradient with respect to the bias equal mean(p − y), with no extra factor?
Show answer
The bias adds directly to the score, so ∂z/∂b = 1. The chain rule then leaves only ∂L/∂z = (p − y)/n per example, and summing over examples gives the mean of p − y.