TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Training and Evaluation: Introduction

Training and Evaluation: Introduction

You can call model.fit(X, y) and get a number back. This course is about the two questions that come right after it: what happened inside fit, and is the number you got believable? The first is training mechanics: how a loss, its gradient and an optimizer move millions of parameters a little at a time. The second is evaluation: which metric matches the decision the model supports, how to split the data so the score predicts the future, and how to find out why a model fails and what to change.

Both halves matter in practice. A model trained with a learning rate ten times too high never converges; a model evaluated on a split that leaks the answer looks perfect and fails on the first real customer. Most of the "my model doesn't work" problems you will meet are one of the two.

The map

training: lower the loss evaluation: measure honestly training loop 18 concepts 8 losses 9 optimizers metrics validation regressionclassificationdetectionsegmentation holdout, k-foldstratified, groupbacktestingexternal diagnose and improve overfitting, leakage, imbalance, tuning, errors, calibration, robustness, shift then: exercises and an evaluation report
Section What you build or measure Labs
The training loop the loop in NumPy for logistic regression and a tiny MLP, then the same loop in PyTorch
Training concepts initialisation, backpropagation, learning rate, batches and epochs, weight decay, dropout, early stopping, checkpoints, schedules, clipping, mixed precision gradient-descent, early-stopping, lr-schedule
Loss functions MSE, MAE, Huber, binary and categorical cross-entropy, focal, contrastive, triplet: formula, code and gradient
Optimizers batch, stochastic and mini-batch GD, momentum, Nesterov, Adagrad, RMSprop, Adam, AdamW, checked against torch.optim gradient-descent
Evaluation metrics MAE to R2R^2, the confusion matrix to ROC-AUC and log loss, IoU, AP, Dice threshold-roc
Validation strategies holdout, k-fold, stratified, group, time-series backtesting, external validation
Diagnosing and improving learning curves, bias and variance, leakage, imbalance, grid/random/Bayesian tuning, error analysis, calibration, robustness, distribution shift bias-variance, leakage, threshold-roc

Training and evaluation in one small program

Here is the whole course in about thirty lines. A logistic-regression model is trained by mini-batch gradient descent on the breast-cancer data that ships with scikit-learn (569 tumours, 30 measurements). Each epoch shuffles the training rows, walks through them in batches of 32, computes the loss and its gradient, and takes one step per batch. After every few epochs the model is scored on a validation set it never trains on. The test set is touched once, at the end.

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)                     # 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_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
sc = StandardScaler().fit(X_tr)                                # fitted on the training part only
X_tr, X_va, X_te = sc.transform(X_tr), sc.transform(X_va), sc.transform(X_te)

def loss_and_grad(w, b, X, y):
    z = X @ w + b
    p = 1 / (1 + np.exp(-z))
    loss = np.mean(np.logaddexp(0, z) - y * z)                 # binary cross-entropy
    return loss, X.T @ (p - y) / len(y), np.mean(p - y)

rng = np.random.default_rng(0)
w, b, lr = np.zeros(X.shape[1]), 0.0, 0.1
for epoch in range(1, 21):
    order = rng.permutation(len(y_tr))
    for start in range(0, len(order), 32):                     # one step per mini-batch
        idx = order[start:start + 32]
        _, gw, gb = loss_and_grad(w, b, X_tr[idx], y_tr[idx])
        w, b = w - lr * gw, b - lr * gb
    if epoch in (1, 5, 10, 20):
        tr_loss = loss_and_grad(w, b, X_tr, y_tr)[0]
        va_loss = loss_and_grad(w, b, X_va, y_va)[0]
        va_acc = np.mean(((X_va @ w + b) > 0) == y_va)
        print(f"epoch {epoch:2d}  train loss {tr_loss:.3f}  val loss {va_loss:.3f}  val accuracy {va_acc:.3f}")
print(f"{len(y_tr)} train, {len(y_va)} validation, {len(y_te)} test rows; {int(np.ceil(len(y_tr) / 32))} steps per epoch")
print("test accuracy, measured once:", round(float(np.mean(((X_te @ w + b) > 0) == y_te)), 3))
epoch  1  train loss 0.229  val loss 0.230  val accuracy 0.965
epoch  5  train loss 0.126  val loss 0.119  val accuracy 0.974
epoch 10  train loss 0.101  val loss 0.092  val accuracy 0.965
epoch 20  train loss 0.083  val loss 0.074  val accuracy 0.982
341 train, 114 validation, 114 test rows; 11 steps per epoch
test accuracy, measured once: 0.974

Every line of it is a topic of this course:

  • The loop (batch, forward pass, loss, gradient, update, next batch, next epoch, validation) is the training loop. Here the gradient is written by hand; for a network it comes from backpropagation.
  • lr = 0.1 and batches of 32 are hyperparameters with their own lessons: the learning rate and batch size, iterations and epochs. The update itself is plain mini-batch SGD, the first of nine optimizers.
  • The loss is binary cross-entropy, one of the eight losses of the course, computed with logaddexp so it cannot overflow.
  • Accuracy is only one of many metrics, and with 114 validation rows one mistake moves it by almost 0.01: the validation accuracy goes 0.965, 0.974, 0.965, 0.982 while the loss falls steadily. The three-way split, the scaler fitted on the training part only and the single look at the test set are the validation strategy and the leakage rules.
  • Comparing training and validation loss is the start of diagnosing over- and underfitting. Here the validation loss (0.074 after 20 epochs) is even a little below the training loss (0.083): no sign of overfitting yet, and on 114 rows such a small difference is noise.

What you should know first

The course follows Classical ML Algorithms, where you met logistic regression, trees and boosting and fitted linear regression by gradient descent. It uses the splits and pipelines of Data Preparation (split strategies, nested cross-validation, the leakage rules). The math (gradients, the chain rule, expectations) is derived in the Mathematics track; lessons link to the exact page, for example gradient descent, backpropagation and automatic differentiation and loss functions.

How examples run here

Every ```python run example runs in your browser (Python in WebAssembly, with NumPy, pandas, SciPy, Matplotlib and scikit-learn), with fixed seeds and rounded printing, so the output you get is the output shown. Training is written in NumPy first, so you can read and change every step. A few examples use PyTorch or Optuna, which cannot run in a browser: they are marked Recorded and show the output of a real run on a CPU (no GPU). Data comes from generators and from the small data sets bundled with scikit-learn, so nothing is downloaded while you learn.

Test yourself

In the example, the training set has 341 rows and the batch size is 32. How many parameter updates happen in one epoch?

  1. 1
  2. 10
  3. 11
  4. 341

Why is the scaler fitted on X_tr only and then applied to the validation and test rows?

  1. It is faster
  2. So no statistic of the validation or test data leaks into training, and the scores stay honest
  3. Because StandardScaler cannot be fitted twice
  4. To make the training loss smaller

The validation accuracy is 0.982 on 114 rows. How much does one more or one fewer correct prediction change it?

  1. About 0.0001
  2. About 0.009
  3. About 0.1
  4. Not at all

What is the validation set used for in this program?

  1. Computing the gradient
  2. Watching progress during training and making choices, while the test set is kept for one final measurement
  3. Replacing the test set
  4. Shuffling the batches