# Supervised learning explained: losses, generalisation and honest evaluation, step by step

Supervised learning fits a function from labelled examples by minimising a loss. This guide walks through the formulas, a worked example with real numbers, runnable scikit-learn 1.9 code and the evaluation mistakes that make good-looking models fail in production.

Supervised learning is the oldest and still the most used way to train a model. You give the algorithm inputs together with the answers you want, such as house features with prices or emails with a spam label, and it adjusts its parameters until its predictions match the answers as closely as a chosen loss function can measure. Almost every other method on this site borrows from it. Supervised fine-tuning of a language model is supervised learning on text. A reward model in RLHF is a supervised classifier trained on human preferences.

The idea is simple, but the details decide whether a model works on data it has never seen. This article teaches those details in order: the objective and its formulas, a worked example you can check by hand, runnable code on current scikit-learn, the ways evaluation goes wrong, and how the same ideas sit inside today's large models.

## What happened

### scikit-learn 1.9.1 is the current stable release (10 September 2026)

The scikit-learn project published version 1.9.1 on PyPI on 10 September 2026, a maintenance release of the 1.9 series that arrived on 2 June 2026. Two changes in 1.9 matter for supervised evaluation. A new function, `sklearn.metrics.metric_at_thresholds`, computes any metric across every decision threshold of a binary classifier, which makes threshold tuning a one-line job. And `log_loss` now names its probability argument `y_proba` instead of `y_pred`, a small rename that makes it harder to pass hard labels to a loss that expects probabilities. Both are documented in the function docstrings that ship with the release.

### PyTorch 2.15 becomes the current deep learning baseline (28 October 2026)

PyTorch 2.15.0 was uploaded to PyPI on 28 October 2026. For supervised learning the loss functions you use every day, such as `nn.CrossEntropyLoss` and `nn.MSELoss`, behave as before, so code in this article runs unchanged. The release matters mostly for teams training at scale, where the same supervised objective is spread across many GPUs.

## The objective: what supervised learning minimises

A supervised dataset is a list of pairs (x_i, y_i). The model is a function f(x; θ) with parameters θ. Training chooses θ to minimise the average loss over the training set, called the empirical risk:

L(θ) = (1/n) · Σ_i ℓ(f(x_i; θ), y_i) + λ · R(θ)

The first term rewards fitting the data. The second term, a regulariser R such as the squared size of the weights, penalises complexity, and λ sets how much. What you really want is low loss on new data from the same source, the expected risk. You can never compute it directly, so you estimate it on data the model did not train on.

Two problem types cover most cases:

- **Regression** predicts a number. The usual loss is mean squared error, MSE = (1/n) Σ (y_i − ŷ_i)². It punishes large errors heavily because errors are squared. Mean absolute error, MAE = (1/n) Σ |y_i − ŷ_i|, is gentler on outliers. Huber loss uses squared error for small errors and absolute error for large ones.
- **Classification** predicts a class. The model outputs probabilities and the loss is cross-entropy, also called log loss. For a binary label it is ℓ = −[y · log p + (1 − y) · log(1 − p)], where p is the predicted probability of class 1. For many classes the model produces scores (logits), a softmax turns them into probabilities, and the loss is −log of the probability given to the correct class.

The loss is not a free choice. Minimising MSE gives you the conditional mean of y given x. Minimising MAE gives the conditional median. Minimising cross-entropy gives calibrated probabilities when the model is flexible enough and the data is plentiful. Pick the loss that matches the question you want answered. You can explore how the shapes differ in the [loss functions simulation](/ai-simulations/loss-functions).

## A worked example you can check by hand

Take three classification examples with true labels y = (1, 0, 1) and predicted probabilities p = (0.9, 0.2, 0.6).

- Example 1: −log(0.9) = 0.105
- Example 2: the label is 0, so the loss is −log(1 − 0.2) = −log(0.8) = 0.223
- Example 3: −log(0.6) = 0.511

The mean cross-entropy is (0.105 + 0.223 + 0.511) / 3 = 0.280. Notice how the third example, a correct but unsure prediction, costs five times more than the first. Cross-entropy rewards confidence when it is right and punishes it hard when it is wrong. A prediction of 0.99 for a true 1 costs 0.010, while a prediction of 0.01 for a true 1 costs 4.605. One confident mistake can outweigh hundreds of good predictions, which is why log loss is sensitive to badly calibrated models.

For regression, take true values (3, 5, 8) and predictions (2.5, 5.5, 6.0). The errors are −0.5, 0.5 and −2. MSE is (0.25 + 0.25 + 4) / 3 = 1.5. MAE is (0.5 + 0.5 + 2) / 3 = 1.0. The single error of 2 supplies 89 percent of the MSE but only 67 percent of the MAE. That is the outlier sensitivity in one line of arithmetic.

How does training reduce these numbers? With gradient descent. For logistic regression the gradient of the cross-entropy with respect to the weights is (p − y) · x for each example, which is surprisingly tidy: the update is proportional to the error. The [logistic regression simulation](/ai-simulations/logistic-regression-gradient-descent) shows the decision boundary moving as these gradients accumulate, and the [linear regression simulation](/ai-simulations/linear-regression) does the same for squared error.

## Generalisation: why a model works on new data, or does not

A model generalises when its loss on new data is close to its loss on training data. The gap between the two is the generalisation gap. Three forces control it.

**Capacity.** A flexible model can fit anything, including noise. A rigid one cannot fit the real pattern. This is the bias and variance trade-off: high bias means systematic error from a model that is too simple, high variance means predictions that change a lot with the particular training sample. Think of a tailor. A one-size suit fits nobody well (bias). A suit cut to a single photograph of you fits that photo perfectly and nothing else (variance).

**Regularisation.** Penalties such as L2 (ridge) and L1 (lasso), early stopping, dropout and data augmentation all reduce variance at some cost in bias. In scikit-learn's `LogisticRegression` the parameter `C` is the inverse of the regularisation strength, so a small C means a strong penalty. The [overfitting and regularisation simulation](/ai-simulations/overfitting-and-regularisation) lets you push a polynomial past the point where it starts fitting noise.

**Data.** More independent examples shrink variance. Duplicates and near-duplicates do not, and they leak information between training and test sets.

Deep networks complicate the classic picture. Very large models can fit the training set exactly and still generalise. Nakkiran and colleagues documented "deep double descent": test error falls, rises near the point where the model can just interpolate the data, then falls again as size keeps growing. In practice this means you should not assume that a bigger model will overfit. You should measure.

| Symptom | Training loss | Validation loss | Likely cause | First fix |
|---|---|---|---|---|
| Underfitting | High | High | Model too simple, too much regularisation | More features or capacity, weaker penalty |
| Overfitting | Low | Much higher | Too much capacity for the data | Stronger penalty, more data, early stopping |
| Leakage | Low | Suspiciously low | Test information in training | Fix the split, rebuild features inside folds |
| Shift | Low | Fine offline, bad live | Production data differs | Monitor inputs, retrain on recent data |

## Evaluation: estimating performance honestly

The rule is simple: never judge a model on data that influenced any decision about it. That includes the weights, the hyperparameters, the feature choices and the threshold.

**Split three ways.** Use a training set to fit, a validation set (or cross-validation) to choose hyperparameters, and a test set touched once at the end. If you look at the test set repeatedly and keep the best run, the test score becomes optimistic.

**Use cross-validation when data is small.** K-fold cross-validation splits the training data into k parts, trains on k − 1 and scores on the remaining one, and averages over k rounds. Stratified folds keep class proportions equal. Grouped folds keep all rows from one patient, user or document in the same fold. Time-series folds always train on the past and test on the future. The [model evaluation simulation](/ai-simulations/train-evaluation) walks through these choices.

**Pick metrics that match costs.** Accuracy hides problems when classes are imbalanced. A fraud model that always says "not fraud" can be 99.5 percent accurate. Use ROC AUC for ranking quality, log loss or the Brier score for probability quality, and precision, recall or F1 at a chosen threshold for decisions.

**Tune the threshold separately.** Many classifiers output a probability and a default threshold of 0.5 turns it into a decision. That default is rarely optimal. The [precision and recall threshold simulation](/ai-simulations/precision-recall-threshold) shows how moving it trades false positives for false negatives.

## Runnable code: the full loop in scikit-learn 1.9

The script below fits a regularised logistic regression on the breast cancer dataset that ships with scikit-learn, chooses C by stratified 5-fold cross-validation on log loss, scores the held-out test set once, and uses the new `metric_at_thresholds` function to find the threshold that maximises F1.

```python
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score, f1_score, metric_at_thresholds

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.25, stratify=y, random_state=0)

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for C in [0.001, 0.1, 1.0, 100.0]:
    model = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=5000))
    scores = cross_val_score(model, X_tr, y_tr, cv=cv, scoring="neg_log_loss")
    print(f"C={C:<6} CV log loss = {-scores.mean():.3f} (+/- {scores.std():.3f})")

best = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=5000)).fit(X_tr, y_tr)
p = best.predict_proba(X_te)[:, 1]
print(f"test log loss {log_loss(y_te, p):.3f}  ROC AUC {roc_auc_score(y_te, p):.3f}")

f1s, thr = metric_at_thresholds(y_te, p, f1_score)
i = int(np.argmax(f1s))
print(f"best F1 {f1s[i]:.3f} at threshold {thr[i]:.3f}; F1 at 0.5 = {f1_score(y_te, p >= 0.5):.3f}")
```

On scikit-learn 1.9.1 it prints:

```text
C=0.001  CV log loss = 0.393 (+/- 0.024)
C=0.1    CV log loss = 0.098 (+/- 0.023)
C=1.0    CV log loss = 0.076 (+/- 0.029)
C=100.0  CV log loss = 0.282 (+/- 0.183)
test log loss 0.086  ROC AUC 0.995
best F1 0.978 at threshold 0.405; F1 at 0.5 = 0.967
```

Read the numbers as a story. With C = 0.001 the penalty is so strong that the model underfits, and log loss is 0.393. With C = 100 the penalty is almost gone and log loss rises to 0.282, with a fold-to-fold spread of 0.183, the signature of high variance. C = 1.0 sits in the valley. The scaler lives inside the pipeline, so it is refit on each training fold and never sees validation rows, which avoids a quiet form of leakage.

One caution about the last line. Here the threshold was tuned on the test set purely to demonstrate the function. In real work you tune it on validation data or inside cross-validation, for example with scikit-learn's `TunedThresholdClassifierCV`, and report the test score at the chosen threshold.

## What goes wrong in practice

**Leakage through preprocessing.** Fitting a scaler, an imputer or a target encoder on the whole dataset before splitting lets test statistics flow into training. Put every fitted step in a pipeline.

**Leakage through time and identity.** Random splits on time-ordered data let the model peek at the future. Random splits on repeated users let it memorise people. Split by time or by group.

**Label noise.** Real labels are wrong some of the time. Cross-entropy chases confident mistakes, so a few mislabelled rows can bend the model. Check the highest-loss training examples by hand. Many turn out to be label errors.

**Miscalibration.** Modern neural networks are often overconfident. Guo and colleagues showed that a single temperature parameter, fitted on validation data after training, fixes much of it. Calibration matters whenever someone acts on the probability, not just the ranking.

**Distribution shift.** A model is only promised to work on data like its training data. When inputs drift, offline metrics stop predicting live performance. Monitor inputs and outcomes after deployment.

## How supervised learning sits inside today's models

Large language models are pretrained with a self-supervised next-token objective, but most of what happens next is supervised. Supervised fine-tuning (SFT) trains on prompt and response pairs with exactly the cross-entropy above, usually computed only on the response tokens. In TRL 1.18.2, `SFTConfig` exposes `assistant_only_loss` and `completion_only_loss` for this purpose, with a default learning rate of 2e-5. The [post-training simulation](/ai-simulations/train-post-training-sft-dpo) shows where SFT sits before preference optimisation.

Reward models used in RLHF are supervised too. They learn a scalar score from pairs labelled "chosen" and "rejected" using a pairwise logistic loss, which is binary cross-entropy on the score difference. Classifiers that filter pretraining data, detect unsafe prompts or route requests between models are all ordinary supervised classifiers, and they live or die by the evaluation habits described here. For tabular problems, gradient boosting and tabular foundation models are the current strong baselines, and both are judged with the same cross-validation discipline.

## What it means in practice

Supervised learning is a contract: if new data looks like the training data, the model's validation score is a fair forecast. Most production failures break that contract rather than the algorithm. Choosing the loss decides what the model estimates. Choosing the split decides whether your score means anything. Choosing the threshold decides what the business actually experiences. The fitting step itself is the easy part and libraries do it well.

## What to do now

1. **Write down the question first.** Decide whether you need a mean, a median, a probability or a ranking, then pick MSE, MAE, cross-entropy or a ranking loss to match.
2. **Build a pipeline before a model.** Put scaling, imputation and encoding inside a scikit-learn `Pipeline` so cross-validation refits them per fold.
3. **Split the way production works.** Use time-based splits for forecasting and grouped splits when the same user or document appears many times.
4. **Start with a simple baseline.** A regularised linear model or gradient boosting gives a number every complex model must beat.
5. **Tune regularisation with cross-validation.** Search C, alpha or depth on a log scale and look at the spread across folds, not only the mean.
6. **Report probability quality.** Track log loss or the Brier score alongside accuracy or F1, and calibrate if probabilities drive decisions.
7. **Tune the threshold on validation data.** Use `metric_at_thresholds` to see the whole curve and `TunedThresholdClassifierCV` to choose a threshold safely.
8. **Read the worst errors.** Sort training rows by loss and inspect the top fifty for label noise and leakage.
9. **Touch the test set once.** Freeze every decision before you score it, then monitor live data after deployment.

## Risks and open questions

**Benchmarks overstate real performance.** Public test sets get reused until models and researchers overfit them. A fresh, private test set is the only reliable check.

**Labels encode human choices.** If the labels reflect past biased decisions, a perfectly fitted model reproduces the bias. Audit error rates across relevant groups.

**Generalisation in very large models is not fully explained.** Double descent and benign overfitting show that classic capacity arguments are incomplete for deep networks. Treat theory as a guide and measurement as the judge.

**Watch next:** how scikit-learn's threshold tools evolve after 1.9, and how post-training libraries such as TRL change their supervised fine-tuning defaults, since small loss masking choices change what an LLM learns.

## Frequently asked questions

### What is the difference between supervised and unsupervised learning?

Supervised learning trains on inputs paired with target labels and learns to predict those labels. Unsupervised learning has no labels and looks for structure such as clusters or low-dimensional directions. Self-supervised learning sits between them by creating labels from the data itself, for example the next word in a sentence.

### Should I use accuracy, F1 or log loss?

Use log loss or the Brier score when you care about the quality of the probabilities. Use F1, precision or recall at a fixed threshold when a decision is made and the costs of the two error types differ. Accuracy is fine only when classes are balanced and both errors cost about the same.

### How many folds should cross-validation use?

Five or ten folds is the usual choice and both work well. More folds reduce bias in the estimate but cost more compute and can increase variance. With very small datasets, repeated stratified k-fold gives a steadier estimate.

### Why is my validation score much better than production?

The usual causes are leakage, such as preprocessing fitted on all data or random splits on time-ordered rows, and distribution shift between historical and live data. Rebuild the split to mirror how predictions are made in production and compare input distributions.

### Is supervised fine-tuning of an LLM really supervised learning?

Yes. SFT minimises cross-entropy between the model's next-token distribution and the tokens of a target response, which is multi-class classification repeated at each position. The main differences are scale and the choice of which tokens count in the loss.

## Summary

Supervised learning fits a model to labelled examples by minimising a loss: squared or absolute error for numbers, cross-entropy for classes. Regularisation trades a little bias for less variance, and cross-validation estimates how well that trade generalises. In the worked example, three predictions gave a cross-entropy of 0.280 and a regression MSE of 1.5, and the scikit-learn 1.9 script showed underfitting at C = 0.001, overfitting at C = 100 and a sweet spot at C = 1.0 with a test ROC AUC of 0.995. The same objective and the same evaluation discipline power SFT and reward models in today's LLMs. For a broader route through these ideas, follow the [machine learning foundations path](/paths/machine-learning-foundations) or browse [evaluation topics](/topics/machine-learning/evaluation).

## Sources

- [scikit-learn: Release highlights for scikit-learn 1.9](https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_1_9_0.html)
- [scikit-learn: Version 1.9 changelog](https://scikit-learn.org/stable/whats_new/v1.9.html)
- [PyPI: scikit-learn 1.9.1](https://pypi.org/project/scikit-learn/1.9.1/)
- [scikit-learn: Cross-validation, evaluating estimator performance](https://scikit-learn.org/stable/modules/cross_validation.html)
- [scikit-learn: Tuning the decision threshold for class prediction](https://scikit-learn.org/stable/modules/classification_threshold.html)
- [PyTorch: PyTorch 2.15 release blog](https://pytorch.org/blog/pytorch-2-15-release-blog/)
- [arXiv: On Calibration of Modern Neural Networks (Guo et al., 2017)](https://arxiv.org/abs/1706.04599)
- [arXiv: Deep Double Descent (Nakkiran et al., 2019)](https://arxiv.org/abs/1912.02292)
