Skip to main content

Supervised Learning

Docs: scikit-learn supervised learning · Cross-validation · Ensembles · Validation curves

Overview​

Supervised learning trains a model on labelled input-output pairs and generalises the mapping to inputs it hasn't seen. This page owns the ideas every model shares: how to split data, cross-validation, the bias–variance trade-off, regularisation and ensembles. The two model pages build on it. The failure people hit is judging a model on the data it trained on, then watching it collapse on anything new.

Key concepts​

Regression or classification​

The target type picks the page.

ProblemTargetExamplesPage
RegressionContinuous valueDemand forecast, house price, sensor readingRegression (bike-rental demand)
ClassificationDiscrete classSpam, diagnosis, machine failureClassification (machine failure, 3% positive)

Train, validation, test​

SplitPurposeTypical share
TrainThe model learns its parameters here70–80%
ValidationTune hyperparameters, compare models10–15%
TestFinal unbiased estimate. Touch once10–15%

Use stratified splits for imbalanced classification. For temporal data, split by time: see choosing the validation split.

Cross-validation​

A single validation split wastes rows and gives a noisy estimate. K-fold cross-validation splits the training data into k folds (k = 5 by default), trains on k − 1 and validates on the held-out fold, rotating k times. Every row is used for both training and validation.

VariantUse whenResult on the wrong data
K-foldRegression, rows exchangeable—
Stratified k-foldClassification: equal class ratios per foldPlain k-fold on 3% positives leaves some folds with almost no failures
TimeSeriesSplitTemporal data: always validate on later data❌ Random k-fold on monthly snapshots over-reports AUC by 0.08 (why)

Fit every scaler and encoder inside each fold, with a Pipeline. Fitting preprocessing on all the data first leaks validation information into training (the pipeline pattern).

Bias–variance trade-off​

As a model gets more flexible, training error keeps falling. Validation error falls, bottoms out, then rises again.

model complexity →errorsweet spottrainingvalidationunderfit · high biasoverfit · high variance

Figure M0-1: Error against model complexity. Grey is training error, red is validation error, amber marks the complexity to pick.

High bias (underfitting)High variance (overfitting)
SymptomHigh train error, high validation errorLow train error, high validation error
CauseModel too simpleModel too flexible for the data
FixMore features, more flexible modelRegularisation, more data, shallower trees, early stopping

Regularisation​

Regularisation adds a penalty for complexity, moving a model left on Figure M0-1.

TypePenaltyEffectOwner section
L1 (Lasso)Sum of absolute weightsDrives some weights to exactly zero: feature selectionLasso
L2 (Ridge)Sum of squared weightsShrinks all weights; stable with correlated featuresRidge
ElasticNetL1 + L2Sparsity that keeps correlated groups togetherElasticNet

Trees regularise differently: max_depth, minimum samples per leaf, and for boosting, learning rate plus early stopping.

Ensembles: bagging vs boosting​

Both combine many trees. They fix opposite problems.

Bagging trains deep trees in parallel on bootstrap samples and averages them; boosting trains shallow trees in sequence on residuals and sums themBagging trains deep trees in parallel on bootstrap samples and averages them; boosting trains shallow trees in sequence on residuals and sums them

Figure M0-2: Bagging and boosting. Blue is a tree, grey is what each tree is trained on, amber is the combining step.

Bagging (Random Forest)Boosting (XGBoost, LightGBM, CatBoost)
TreesDeep, independent, in parallelShallow, each fits the previous ensemble's errors
FixesVariance (overfitting)Bias (underfitting)
TuningWorks almost out of the boxNeeds learning rate, depth and early stopping
Typical resultStrong baselineBest tabular accuracy once tuned
Failure modeBiased feature_importances_No early stopping → overfit

Pages in this section​

Each model page opens with a cheatsheet table and threads one running example through every model, so the trade-offs are directly comparable.

PageRunning exampleCovers
RegressionBike-rental demandLinear, Ridge/Lasso/ElasticNet, polynomial, trees, ensembles, SVR; RMSE vs MAE
ClassificationMachine failure (3% positive)Logistic regression, trees, ensembles, SVM, KNN, Naive Bayes, MLP; thresholds and imbalance

For the stages around model choice (framing, preprocessing, features, production), see the ML Project Lifecycle.

Gotchas​

  • Scoring on training data. A memorising model looks perfect. Report validation or cross-validated scores only.
  • Tuning against the test set. It stops being an unbiased estimate. Tune on validation; score the test set once.
  • Preprocessing before splitting. Statistics leak across folds. Put every fitted step in a Pipeline.
  • Plain k-fold on rare classes or time series. Folds lose positives, or validate on the past. Use stratified or time-based splits.
  • Adding regularisation to an underfit model. It makes bias worse. Check which side of Figure M0-1 you're on first.

Scenario questions​

Q1 ★ Training accuracy is 99%, validation is 72%. What's going on?

Model answer
  • Clarify: what model, how much data, and how was validation drawn?
  • Observe: the gap between training and validation error is large; training error is near zero.
  • Hypothesise: high variance. The model memorised the training set. Less likely: leakage in training only, or a distribution shift between splits.
  • Fix: regularise (shallower trees, stronger penalty, early stopping) or add data.
  • Prevent: track training and validation curves together. The trade-off is a little training accuracy for generalisation.

Q2 ★★ When would you pick Random Forest over XGBoost?

Model answer
  • Clarify: how much tuning time is there, and how much accuracy matters?
  • Observe: on the machine-failure data, the untuned forest scores PR-AUC 0.40; tuned XGBoost 0.46.
  • Hypothesise: the forest reduces variance with almost no tuning. Boosting reduces bias but needs early stopping and a search.
  • Fix: forest for a fast, robust baseline; boosting when the extra accuracy is worth the tuning bill.
  • Prevent: always have the forest as the baseline boosting must beat. The trade-off is one more model to train.

Q3 ★★ Why not just report one train/validation split?

Model answer
  • Clarify: how big is the data, and is it temporal?
  • Observe: scores vary by a few points across different random splits.
  • Hypothesise: a single split is a noisy estimate, and a lucky split flatters the model.
  • Fix: k-fold (stratified for classification), or a time-based split for temporal data, reporting the mean and spread.
  • Prevent: cross-validation inside a pipeline as the default. The trade-off is k times the training cost.

Summary​

  • Generalisation is the goal. Only scores on data the model didn't train on count.
  • Split the way you'll predict. Stratified for rare classes, by time for temporal data.
  • Watch both error curves. The gap between training and validation tells you bias from variance.
  • Regularisation moves you left. Use it against variance, never against bias.
  • Bagging cancels variance, boosting cancels bias. Forest for a robust baseline, boosting for the best tuned accuracy.

Next → Regression