Supervised learning, bias–variance & overfitting

In one sentence

Supervised learning fits a function from labeled examples; what matters is error on unseen data, so you hold data out to measure it and balance underfitting (high bias) against overfitting (high variance).

Analogy: A student who memorizes last year's exam aces the practice test and fails the real one (overfitting). One who only learned "when in doubt, pick C" fails both (underfitting).

The train–validation gap is the diagnosis: both high means underfit, a large gap means overfit. The test set is only for the final number.

How it works

  • Split data: train fits weights, validation picks hyperparameters, test is touched once for the reported number.
  • With little data, use k-fold cross-validation: train k times and average the scores.
  • Expected error = bias² + variance + irreducible noise; more capacity lowers bias and raises variance.
  • Underfit: train and validation error are both high. Overfit: train is low, validation much higher.
  • A learning curve shows if more data helps: a gap that shrinks as data grows says yes.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your learning curve shows train and validation error both high, flat and close together as training size grows. Your PM offers budget to label 3× more data. What do you recommend?

Go deeper

Full explanation

Supervised learning fits a function f(x) → y from labeled examples: regression when y is a number, classification when it's a class. The only score that matters is generalization: error on data the model has never seen. So you hold data out:

  • Train (~70–80%): fits the weights.
  • Validation (~10–15%): chooses hyperparameters and models.
  • Test (~10–15%): touched once, for the number you report.

With little data, use k-fold cross-validation (k = 5 or 10): train k times, each fold is the validation set once, average the scores.

Expected error on new data splits into bias² + variance + irreducible noise:

  • Underfitting (high bias): the model is too simple for the pattern. Train and validation error are both high.
  • Overfitting (high variance): the model memorizes noise. Train error is low, validation error much higher.

More capacity lowers bias and raises variance: that's the trade-off. A learning curve (error vs. training-set size) tells you which side you're on: a big gap that shrinks as data grows means more data will help; two flat, high curves mean it won't.

  • Underfit → bigger model, better features, less regularization, train longer.
  • Overfit → more data, Regularization, simpler model, early stopping.
Code Complexity sweep, cross-validation and learning curve (sklearn)
pythonComplexity sweep, cross-validation and learning curve (sklearn)
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_score, learning_curve
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=5000, n_features=20, n_informative=10,
                           flip_y=0.1, random_state=0)   # 10% of labels randomized
# Carve out the test set FIRST; it is not touched until the very end
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)

# Complexity sweep: shallow trees underfit (high bias), unlimited depth overfits (high variance)
for depth in [1, 4, 8, None]:
    m = DecisionTreeClassifier(max_depth=depth, random_state=0)
    train = m.fit(X_dev, y_dev).score(X_dev, y_dev)
    cv = cross_val_score(m, X_dev, y_dev, cv=5).mean()      # 5-fold CV on dev only
    print(f"depth={depth}: train={train:.2f} cv={cv:.2f} gap={train - cv:.2f}")
# depth=1: 0.60 / 0.59 (underfit) ... depth=8: 0.90 / 0.83 ... None: 1.00 / 0.80 (overfit)

# Learning curve of the overfit model: does more data close the gap?
sizes, tr, va = learning_curve(DecisionTreeClassifier(random_state=0), X_dev, y_dev,
                               cv=5, train_sizes=np.linspace(0.1, 1.0, 4))
for n, a, b in zip(sizes, tr.mean(axis=1), va.mean(axis=1)):
    print(f"n={n}: train={a:.2f} val={b:.2f}")   # val still rising => more data helps

final = DecisionTreeClassifier(max_depth=8, random_state=0).fit(X_dev, y_dev)  # chosen by CV
print(f"test={final.score(X_test, y_test):.2f}")   # report once, never tune on it
Real example

A churn model (gradient-boosted trees, depth 12, 1,000 trees) scores 0.99 AUC on train and 0.74 on validation: a 0.25 gap, classic overfitting. The learning curve shows validation AUC still climbing at the full 40k rows, but there is no more data. You cut depth to 6, require 100 rows per leaf and stop adding trees when validation AUC stalls: train 0.86, validation 0.82. Then you notice the same users appear in both splits; re-splitting by user drops validation to 0.79, the honest number. Test AUC, measured once: 0.79.

Trade-offs +3 · −3

+ You gain

  • The train–validation gap is a cheap, model-agnostic diagnostic that tells you which lever to pull.
  • k-fold CV uses every row for both training and validation, and gives an error bar (std across folds).
  • An untouched test set is your only unbiased estimate on new data from the same distribution.

− You pay

  • k-fold costs k× the training compute; for large deep nets a single holdout is the norm.
  • Random splits lie on time series, grouped data (same user in train and val) and near-duplicates.
  • Hundreds of tuning runs against one validation set slowly overfit it too.

Use it when

Always: every supervised model needs a held-out estimate. Use k-fold CV when data is small and training is cheap (most tabular work); a fixed train/val/test split when training is expensive.

Avoid it when

Don't shuffle-split time series (use forward-chaining, e.g. TimeSeriesSplit) or grouped data (use GroupKFold), and don't k-fold a model that takes days to train.

Numbers to know 4
  • Expected squared error = bias² + variance + irreducible noise σ².
  • Split rule of thumb: 80/10/10 or 70/15/15; with millions of examples, 98/1/1 still leaves 10k+ rows for val and for test.
  • k = 5 or 10 folds; Kohavi (1995) recommended stratified 10-fold CV for model selection.
  • Test noise: at ~90% accuracy on 1,000 examples, the 95% confidence interval is about ±1.9 points.
Common pitfalls 4
  • Leakage: fitting the scaler, imputer or feature selection on all data before splitting. Put preprocessing in a Pipeline so it's fit per fold.
  • Random splits on time series or grouped data: the same user in train and val inflates every metric.
  • Peeking at the test set to pick a model: its number stops being an unbiased estimate.
  • Assuming validation looks like production: a great score on last year's data says little after drift.
Interview questions 3

Answer out loud first, then reveal.

Train accuracy is 98%, validation 75%. What do you do?Show answer

That 23-point gap says high variance, but first I rule out a broken split: leakage, duplicates, or train and validation from different periods or users. If the split is sound, I plot a learning curve. If validation is still climbing with more data, the best fix is more or augmented data. Otherwise I cut effective capacity: stronger regularization, early stopping, fewer or better features, a smaller model. I change one lever at a time, track the gap on validation and keep the test set untouched until the end.

Explain the bias–variance trade-off.Show answer

Expected error on new data is bias squared plus variance plus irreducible noise. Bias is systematic error from wrong assumptions, like a straight line through curved data: it misses the same way whatever the training sample. Variance is sensitivity to the particular sample: retrain on fresh data and you get a different model. More capacity lowers bias and raises variance. Bagging mainly cuts variance, boosting mainly cuts bias. One caveat: huge over-parameterized networks show double descent and generalize well past the classic sweet spot, so I diagnose with validation curves instead of assuming a U-shape.

When does random k-fold cross-validation give you the wrong answer?Show answer

Whenever rows aren't independent. With time series, random folds let the model train on the future and predict the past, so I use forward-chaining splits that mimic deployment. With grouped data, like many rows per user or patient, the model recognizes the entity instead of learning the pattern, so I use GroupKFold. With near-duplicates, I dedupe before splitting. With heavy class imbalance I stratify so every fold has the rare class. The rule: the split must mimic how the model meets data in production.