TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › A Training Loop in NumPy: Logistic Regression

A Training Loop in NumPy: Logistic Regression

The previous lesson ran the training loop on linear regression, where every number can be checked by hand. Now give the loop a real job: decide whether a tumour is malignant or benign from 30 measurements, with logistic regression trained by mini-batch gradient descent. You will write it as reusable functions (forward, loss, gradient, one epoch, evaluation) because the next lesson swaps in a neural network and keeps everything else.

Classical ML Algorithms fitted the same model with Newton's method on all the data at once. Newton's method needs the Hessian, a d×dd \times d matrix, which is fine for 30 features and impossible for a network with millions of parameters. Gradient descent needs only the gradient, one number per parameter, and processes the data in small batches, so it scales to any model and any data size.

The pieces

For a batch XbX_b (BB rows, dd columns) the forward pass and the prediction are

z=Xbw+b,p^=σ(z)=11+e−z\mathbf{z} = X_b \mathbf{w} + b, \qquad \hat{\mathbf{p}} = \sigma(\mathbf{z}) = \frac{1}{1 + e^{-\mathbf{z}}}

The loss is the mean binary cross-entropy over the batch:

L=−1B∑i=1B[yilog⁡p^i+(1−yi)log⁡(1−p^i)]L = -\frac{1}{B} \sum_{i=1}^{B} \big[ y_i \log \hat{p}_i + (1 - y_i) \log(1 - \hat{p}_i) \big]

Its gradient is short, because the derivative of the sigmoid cancels against the derivative of the logarithm (derivation: Maximum Likelihood and Cross-Entropy):

∇wL=1BXb⊤(p^−yb),∂L∂b=1B∑i=1B(p^i−yi)\nabla_{\mathbf{w}} L = \frac{1}{B} X_b^\top (\hat{\mathbf{p}} - \mathbf{y}_b), \qquad \frac{\partial L}{\partial b} = \frac{1}{B} \sum_{i=1}^{B} (\hat{p}_i - y_i)

The update is plain gradient descent, w←w−η∇wL\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla_{\mathbf{w}} L, with the same for bb.

The full loop

The data are split three ways: 60 % for training, 20 % for validation (to choose the best epoch) and 20 % for the final test (touched once, at the very end). The scaler is fitted on the training part only. The loop records the history, keeps the parameters of the best validation epoch, and stops early when validation has not improved for patience epochs.

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)               # 569 tumours, y = 1 benign
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_val, y_tr, y_val = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
sc = StandardScaler().fit(X_tr)                          # fitted on training rows only
X_tr, X_val, X_te = sc.transform(X_tr), sc.transform(X_val), sc.transform(X_te)
print("train / val / test sizes:", len(y_tr), len(y_val), len(y_te))

def forward(params, X):
    w, b = params
    return 1 / (1 + np.exp(-(X @ w + b)))

def bce(p, y, eps=1e-12):
    p = np.clip(p, eps, 1 - eps)                         # avoid log(0)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

def gradients(params, X, y):
    err = forward(params, X) - y
    return X.T @ err / len(y), err.mean()

def train_epoch(params, X, y, lr, batch_size, rng):
    w, b = params
    order = rng.permutation(len(y))
    for start in range(0, len(y), batch_size):
        idx = order[start:start + batch_size]
        gw, gb = gradients((w, b), X[idx], y[idx])
        w, b = w - lr * gw, b - lr * gb                  # new arrays, old ones untouched
    return w, b

def evaluate(params, X, y):
    p = forward(params, X)
    return bce(p, y), np.mean((p >= 0.5) == y)

rng = np.random.default_rng(0)
params = (np.zeros(X_tr.shape[1]), 0.0)
best = {"loss": np.inf}
patience, wait = 10, 0
for epoch in range(1, 201):
    params = train_epoch(params, X_tr, y_tr, lr=0.1, batch_size=32, rng=rng)
    tr_loss, tr_acc = evaluate(params, X_tr, y_tr)
    val_loss, val_acc = evaluate(params, X_val, y_val)
    if val_loss < best["loss"]:
        best = {"loss": val_loss, "epoch": epoch, "params": params}
        wait = 0
    else:
        wait += 1
    if epoch in (1, 2, 5, 10, 20) or wait == patience:
        print(f"epoch {epoch:3d}  train loss {tr_loss:.4f} acc {tr_acc:.3f}   val loss {val_loss:.4f} acc {val_acc:.3f}")
    if wait == patience:
        print(f"stopped after epoch {epoch}: no improvement for {patience} epochs")
        break

print("best epoch", best["epoch"], " val loss", round(best["loss"], 4))
te_loss, te_acc = evaluate(best["params"], X_te, y_te)
print(f"test (once, best checkpoint): loss {te_loss:.4f}  accuracy {te_acc:.3f}")
train / val / test sizes: 341 114 114
epoch   1  train loss 0.2290 acc 0.947   val loss 0.2296 acc 0.965
epoch   2  train loss 0.1753 acc 0.962   val loss 0.1723 acc 0.974
epoch   5  train loss 0.1260 acc 0.977   val loss 0.1193 acc 0.974
epoch  10  train loss 0.1009 acc 0.979   val loss 0.0925 acc 0.965
epoch  20  train loss 0.0834 acc 0.979   val loss 0.0738 acc 0.982
epoch 178  train loss 0.0547 acc 0.982   val loss 0.0451 acc 0.991
stopped after epoch 178: no improvement for 10 epochs
best epoch 168  val loss 0.045
test (once, best checkpoint): loss 0.0868  accuracy 0.965

What the run shows:

  • Fast start, slow finish. One epoch is 11 updates (⌈341/32⌉\lceil 341/32 \rceil). After the first epoch the model already classifies 94.7 % of the training tumours correctly; the remaining 167 epochs only push the loss from 0.2290 down to about 0.05.
  • Accuracy is a coarse signal. Between epochs 5 and 10 the validation accuracy fell from 0.974 to 0.965 (one tumour of 114) while the validation loss kept improving from 0.1193 to 0.0925. The loss sees confidence, accuracy only sees which side of 0.5 a prediction lands. That is why the loop selects on validation loss.
  • Early stopping. The best validation loss came at epoch 168; ten epochs without improvement later the loop stopped at 178 and kept the epoch-168 parameters.
  • The test score is lower than the validation score (loss 0.0868 against 0.045, accuracy 0.965 against 0.991). Part of that is chance with 114 tumours, and part is selection: the checkpoint was chosen because it did well on the validation set, so the validation score is optimistic. The test set, seen once, is the honest number.

Checking the loop against scikit-learn

A hand-written loop can be subtly wrong and still produce a falling loss. Two cheap checks catch most bugs: compare the analytic gradient with a numerical one (the lesson on backpropagation does this in general), and compare the trained model with a library that minimises the same objective. Without a penalty and trained long enough, gradient descent must reach the same minimum as scikit-learn's LogisticRegression(penalty=None), since the loss is convex. On this nearly separable data the unpenalised minimum lies very far out, so the check uses a small L2 penalty in both: the loss 1n∑BCE+λ2∥w∥2\frac{1}{n}\sum \text{BCE} + \frac{\lambda}{2}\lVert \mathbf{w} \rVert^2 matches scikit-learn's objective with C=1/(nλ)C = 1/(n \lambda).

python · try it yourself
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr = sc.transform(X_tr)
n, lam = len(y_tr), 0.01

def loss(w, b):
    p = 1 / (1 + np.exp(-(X_tr @ w + b)))
    return -np.mean(y_tr * np.log(p) + (1 - y_tr) * np.log(1 - p)) + lam / 2 * w @ w

def grad(w, b):
    p = 1 / (1 + np.exp(-(X_tr @ w + b)))
    return X_tr.T @ (p - y_tr) / n + lam * w, np.mean(p - y_tr)   # penalty gradient: lam * w

# 1. gradient check at a random point, all 30 weights, central differences
w0 = np.random.default_rng(1).normal(scale=0.1, size=X_tr.shape[1])
h, E = 1e-6, np.eye(len(w0))
num = np.array([(loss(w0 + h * E[j], 0.2) - loss(w0 - h * E[j], 0.2)) / (2 * h) for j in range(len(w0))])
print("max |analytic - numerical| gradient:", f"{np.max(np.abs(grad(w0, 0.2)[0] - num)):.1e}")

# 2. full-batch gradient descent to convergence, then compare with scikit-learn
w, b = np.zeros(X_tr.shape[1]), 0.0
for step in range(5000):
    gw, gb = grad(w, b)
    w, b = w - 0.5 * gw, b - 0.5 * gb
sk = LogisticRegression(C=1 / (n * lam), tol=1e-10, max_iter=10000).fit(X_tr, y_tr)
print("max |w_ours - w_sklearn|:", f"{np.max(np.abs(w - sk.coef_[0])):.1e}")
print("bias ours", round(b, 4), " sklearn", round(sk.intercept_[0], 4))
max |analytic - numerical| gradient: 1.1e-10
max |w_ours - w_sklearn|: 1.2e-07
bias ours 0.5146  sklearn 0.5146

The analytic gradient agrees with central differences to about 10−1010^{-10}, and after 5000 full-batch steps the weights agree with scikit-learn's solver to about 10−710^{-7}: the loop minimises the objective it claims to. (The learning rate 0.5 is safe here because the curvature of this loss is small; the lesson on the learning rate shows what happens when it is not.)

Pitfalls

  • log(0). When a prediction saturates at exactly 0 or 1, log⁡p^\log \hat{p} is −∞-\infty and the loss becomes nan. Clip the probabilities, as bce does, or compute the loss from the logits zz with np.logaddexp(0, z) - y * z, which never overflows.
  • Testing every epoch. The test set appears once, after training, on the checkpoint chosen by validation. If you pick the epoch by test accuracy, the test score is no longer an honest estimate.
  • Fitting the scaler on all rows. The validation and test rows must be transformed with the training statistics. See the leakage rules.
  • Unscaled features. The breast-cancer features range from about 0.001 to 2500. Without standardisation, one learning rate cannot suit all weights: it is too big for the large features (divergence) and too small for the tiny ones.

Practice

  1. In the first example the loop stops early. Which epoch does it restore, and why is that not the last one?
Answer

It restores the epoch with the lowest validation loss (printed as "best epoch"). The loop ran patience more epochs after it to make sure validation was not going to improve again; those extra epochs are discarded.

  1. Change batch_size to len(y_tr) (full batch) and keep lr=0.1. How does the number of updates per epoch change, and what do you expect for the number of epochs needed?
Answer

There is one update per epoch instead of ⌈341/32⌉=11\lceil 341/32 \rceil = 11. Each update is less noisy, but there are 11 times fewer of them, so the run needs many more epochs to reach the same loss (and early stopping triggers much later).

  1. Write the gradient of the penalised loss 1n∑BCE+λ2∥w∥2\frac{1}{n}\sum \text{BCE} + \frac{\lambda}{2}\lVert \mathbf{w} \rVert^2 with respect to w\mathbf{w}, and explain why the bias is not penalised.
Answer

∇w=1nX⊤(p^−y)+λw\nabla_{\mathbf{w}} = \frac{1}{n} X^\top (\hat{\mathbf{p}} - \mathbf{y}) + \lambda \mathbf{w}. The bias only shifts the decision boundary and does not make the model more complex; penalising it would push the predicted base rate towards 50 %, which is not what regularisation is for. scikit-learn does not penalise the intercept either.

Test yourself

What is the gradient of the mean binary cross-entropy of logistic regression with respect to w\mathbf{w}?

  1. 1BX⊤(p^−y)\frac{1}{B} X^\top (\hat{\mathbf{p}} - \mathbf{y})
  2. 2BX⊤(p^−y)\frac{2}{B} X^\top (\hat{\mathbf{p}} - \mathbf{y})
  3. 1BX⊤p^(1−p^)\frac{1}{B} X^\top \hat{\mathbf{p}} (1 - \hat{\mathbf{p}})
  4. Xw−yX \mathbf{w} - \mathbf{y}

Why use gradient descent instead of Newton's method for large models?

  1. Newton's method gives wrong answers
  2. Newton's method needs the d×dd \times d Hessian, which is impossible to store or invert for millions of parameters
  3. Gradient descent always converges in fewer steps
  4. Newton's method cannot use a validation set

In the full loop, which data decide which epoch's parameters are kept?

  1. The training set
  2. The validation set
  3. The test set
  4. All three together

Why does bce clip the probabilities?

  1. To speed up training
  2. To keep log⁡p^\log \hat{p} finite when a prediction is exactly 0 or 1
  3. To make the loss convex
  4. To regularise the model