Overfitting, Underfitting and Cross-Validation

Updated · 10 min read
hardPython 3.13aimachine-learningcross-validationoverfittingregularizationdata-leakage

Overfitting is when a model learns its training data too closely, noise included, and does worse on new data. Underfitting is when a model is too simple to capture the real pattern, and does poorly everywhere. Cross-validation is the standard way to estimate how a model will do on new data, so you can find the balance between the two.

This lesson completes the chapter's checkpoint: evaluate the late-fee model with cross-validation and a confusion matrix (the first half, grouping students, is in "Unsupervised Learning and Clustering").

Train, Validation and Test Sets

SetDescriptionWhen it is used
Training setIt is used to fit the modelEvery training run
Validation setIt is used to compare models and settingsWhile choosing; cross-validation makes many of these from the training data
Test setIt is used to give the final, honest estimateOnce, at the end

Underfitting and Overfitting

A validation curve trains the same model with different amounts of flexibility and compares training and validation scores. This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.model_selection import train_test_split, validation_curve
from sklearn.tree import DecisionTreeClassifier
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
depths = [1, 2, 3, 4, 6, 8, 12, 20]
train_scores, val_scores = validation_curve(DecisionTreeClassifier(random_state=0), X_train, y_train,
                                            param_name="max_depth", param_range=depths, cv=5)
for depth, tr, va in zip(depths, train_scores.mean(axis=1), val_scores.mean(axis=1)):
    print(f"depth {depth:2}: training {tr:.1%}  validation {va:.1%}  gap {tr - va:5.1%}")
Output
depth  1: training 85.7%  validation 85.7%  gap  0.0%
depth  2: training 85.8%  validation 85.7%  gap  0.0%
depth  3: training 87.8%  validation 86.7%  gap  1.1%
depth  4: training 89.3%  validation 84.9%  gap  4.4%
depth  6: training 91.9%  validation 86.5%  gap  5.4%
depth  8: training 94.9%  validation 86.3%  gap  8.7%
depth 12: training 98.2%  validation 85.6%  gap 12.6%
depth 20: training 98.5%  validation 85.5%  gap 13.1%
Training scores keep rising; validation scores tell the truth

Explanation: validation_curve runs 5-fold cross-validation for each tree depth and returns training and validation scores.

  • Depths 1 and 2 underfit: 85.7% on both, the same as always guessing "on time". The tree is too simple to learn anything.
  • Depth 3 is the sweet spot: the best validation score, 86.7%, with a small gap.
  • Deeper trees overfit: training accuracy climbs to 98.5%, but validation falls to 85.5%. The gap between the two, 13.1 points at depth 20, is the sign of memorizing.

Bias and Variance

High bias (underfitting)High variance (overfitting)
What it meansThe model is too simple for the patternThe model is too sensitive to the training data
Training scoreLowHigh
Validation scoreLow, close to trainingMuch lower than training
FixesA more flexible model; better featuresMore data; a simpler model; regularization

The best model sits between the two: flexible enough to learn the pattern, constrained enough to ignore noise. This is called the bias-variance trade-off.

Regularization

Regularization adds a penalty for large coefficients, which keeps a model simpler and reduces overfitting. In scikit-learn's LogisticRegression, C controls it: a smaller C means stronger regularization. This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
for C in [0.001, 0.01, 0.1, 1, 10]:                 # smaller C means stronger regularization
    model = make_pipeline(StandardScaler(), LogisticRegression(C=C))
    print(f"C={C:<6} cross-validated accuracy {cross_val_score(model, X_train, y_train, cv=5).mean():.1%}")
Output
C=0.001  cross-validated accuracy 85.7%
C=0.01   cross-validated accuracy 85.7%
C=0.1    cross-validated accuracy 89.3%
C=1      cross-validated accuracy 89.9%
C=10     cross-validated accuracy 89.5%

Explanation: With C=0.001 or 0.01 the penalty is so strong that the model barely uses the features and scores the baseline 85.7%: regularization pushed it into underfitting. C=1, the default, scores best at 89.9%; C=10 is slightly lower. On this small, clean dataset logistic regression hardly overfits, so the default is right; on data with many features, a smaller C often helps.

ModelRegularization setting
LogisticRegressionC (smaller is stronger)
Ridge, Lasso (linear regression)alpha (larger is stronger)
Decision trees, forestsmax_depth, min_samples_leaf
Neural networksDropout, weight decay, early stopping

Data Leakage

Data leakage is when information from outside the training data slips into training, making scores look better than the model really is. A classic cause is preparing data using all of it before splitting. This program shows how big the effect can be, on data with nothing to learn:

Python
import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
 
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 5000))       # 200 examples, 5,000 features of pure noise
y = rng.integers(0, 2, 200)            # random labels: nothing here can be predicted
 
# Leaky: choose the 20 "best" features using ALL the data, then cross-validate
X_picked = SelectKBest(k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_picked, y, cv=5).mean()
 
# Honest: feature selection inside the pipeline, so each fold picks features from its training part only
honest = cross_val_score(make_pipeline(SelectKBest(k=20), LogisticRegression()), X, y, cv=5).mean()
 
print(f"Leaky estimate:  {leaky:.1%}")
print(f"Honest estimate: {honest:.1%}   (guessing scores about 50%)")
Output
Leaky estimate:  79.5%
Honest estimate: 51.0%   (guessing scores about 50%)

Explanation: The labels are random, so no model can honestly beat 50%. The leaky version chooses the 20 features most related to the labels using all 200 examples, including the ones later used for validation, and scores a fake 79.5%. The honest version puts SelectKBest inside the pipeline, so each fold chooses features from its own training part, and scores 51.0%, which is the truth.

Example: The Checkpoint

This program evaluates the late-fee model properly: cross-validation with several metrics, a cross-validated confusion matrix, then one final test. This program uses payments_history.csv from "Supervised Learning".

Python
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict, cross_validate, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
 
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
 
model = make_pipeline(StandardScaler(), LogisticRegression())
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)   # each fold keeps the same share of late payers
 
# 1. Cross-validate on the training data with several metrics at once
cv = cross_validate(model, X_train, y_train, cv=folds, scoring=["accuracy", "recall", "roc_auc"])
for metric in ["accuracy", "recall", "roc_auc"]:
    scores = cv[f"test_{metric}"]
    print(f"{metric:9} folds {scores.round(2)}  mean {scores.mean():.3f}")
 
# 2. A confusion matrix from cross-validation: every training family predicted by a model that never saw it
cm = confusion_matrix(y_train, cross_val_predict(model, X_train, y_train, cv=folds))
print("Cross-validated confusion matrix (rows: real on time, real late):")
print(cm)
 
# 3. One final check on the untouched test set
final = model.fit(X_train, y_train).predict(X_test)
print("Test confusion matrix:")
print(confusion_matrix(y_test, final))
print(f"Test recall on late payers: {recall_score(y_test, final):.3f}")
Output
accuracy  folds [0.91 0.87 0.92 0.89 0.87]  mean 0.895
recall    folds [0.52 0.19 0.62 0.59 0.23]  mean 0.430
roc_auc   folds [0.9  0.8  0.95 0.89 0.83]  mean 0.875
Cross-validated confusion matrix (rows: real on time, real late):
[[625  18]
 [ 61  46]]
Test confusion matrix:
[[210   4]
 [ 21  15]]
Test recall on late payers: 0.417

Explanation:

  1. StratifiedKFold makes 5 folds that each keep the same share of late payers (about 14%), and shuffle=True mixes the rows first. cross_validate scores three metrics at once. Accuracy is steady (0.87 to 0.92), but recall on late payers swings from 0.19 to 0.62. Each fold has only about 21 late payers, so a few families change it a lot. This spread is exactly what a single split would hide.
  2. cross_val_predict predicts every training family with a model that never saw it, so the confusion matrix covers all 750 training families: 46 of 107 late payers caught (recall 0.43), with 18 false alarms.
  3. The test set, used once, agrees: 15 of 36 late payers caught (recall 0.417), with 4 false alarms. The cross-validated estimate was right, and it's the same 0.42 seen in "The Scikit-Learn Workflow".

The model's weak point is clear: it misses more than half of late payers. Lowering the threshold, as in "Evaluating Models: Metrics", and better features, in "Feature Engineering", are the next steps.

Common Mistakes

Tuning on the test set. Choose settings with cross-validation; test once.

Preprocessing before splitting. Scaling, filling or selecting features on all the data leaks information.

Ignoring the spread. A mean of 0.43 with folds from 0.19 to 0.62 is much less certain than it looks.

Plain k-fold on rare classes. Use stratified folds so each fold has its share of positives.

Random splits for time-ordered data. For predicting the future, train on the past and validate on later data (TimeSeriesSplit).

Interview Corner

How do you detect overfitting?

Compare training and validation scores: a high training score with a much lower validation score means overfitting. A validation curve over model complexity shows where it starts.

What is data leakage, and how do you prevent it?

Information from validation or test data, or from the future, reaching the model during training. Prevent it by splitting first, putting every learned preprocessing step in a pipeline, and checking that no feature is only known after the outcome.

Practice

Exercise: a forest's validation curve. Run validation_curve for RandomForestClassifier(n_estimators=100, random_state=0) over min_samples_leaf values 1, 2, 5, 10 and 20. Where does the gap between training and validation shrink, and does validation improve?

Check your understanding:

  1. Which tree depths underfit, and how can you tell?
  2. Why did the leaky version score 79.5% on random labels?
  3. Why did recall vary so much between folds?

Quick check: cross-validation

4 questions
1What signals overfitting in the validation curve?
2What does a smaller C do in LogisticRegression?
3Why was the leaky estimate wrong?
4What did the test set confirm?

Key Takeaways

Quick reference

NeedCode
Validation curvevalidation_curve(model, X, y, param_name=..., param_range=..., cv=5)
Several metricscross_validate(model, X, y, scoring=["accuracy", "recall"])
Stratified foldsStratifiedKFold(n_splits=5, shuffle=True, random_state=0)
Cross-validated predictionscross_val_predict(model, X, y, cv=folds)
RegularizationLogisticRegression(C=0.1), Ridge(alpha=1.0)

Was this tutorial helpful?

Lesson 130 of 186