Section 1 · Lesson 3

Overfitting, underfitting and model complexity

Why a model that aces its training data can fail on new data, and how a validation set helps you pick the right complexity.

40 min 2 practice tasks
Machine Learning Fundamentals: Bias and Variance by StatQuest with Josh Starmer on YouTube

A model’s job is to capture the real pattern in the data while ignoring the noise. Get the balance wrong in one direction and the model underfits; get it wrong in the other and it overfits.

Two ways to fail

  • Underfitting (high bias). The model is too simple to capture the pattern. A tree with one split can’t express “recent cart abandoners on desktop convert a lot”. It scores poorly on training data and test data.
  • Overfitting (high variance). The model is so flexible that it learns the quirks of the particular rows it saw. It scores brilliantly on training data and worse on new data, and if you trained it on a different sample you’d get a very different model.

The bias–variance trade-off says that as complexity grows, bias falls and variance rises. Test error is lowest somewhere in between.

Watching it happen

A decision tree with no depth limit keeps splitting until every leaf is pure. On the training visitors it grows 600 leaves and reaches 100% accuracy. On the test set it scores about 78.7%, which is worse than the 84.7% baseline of predicting that nobody converts. It has memorized individual visitors instead of learning what makes people buy.

Limiting depth shows the trade-off clearly:

max_depth Accuracy on rows it learned from Accuracy on held-out rows
1 0.847 0.848
3 0.871 0.854
5 0.881 0.865
8 0.909 0.850
10 0.937 0.829

Training accuracy keeps climbing as the tree grows. Held-out accuracy rises, peaks and falls. The growing gap between the two columns is overfitting.

Choose complexity with a validation set

You need held-out data to pick max_depth, but if you use the test set for that, it’s no longer an honest final exam. The solution is a three-way split:

  1. Training set: fit each candidate model.
  2. Validation set: compare candidates and pick the best settings.
  3. Test set: score the single chosen model once.
X_fit, X_val, y_fit, y_val = train_test_split(
    X_train, y_train, test_size=0.25, random_state=0, stratify=y_train
)
for depth in range(1, 11):
    tree = DecisionTreeClassifier(max_depth=depth, random_state=42).fit(X_fit, y_fit)
    print(depth, tree.score(X_fit, y_fit), tree.score(X_val, y_val))

After choosing, refit on the whole training set so the final model learns from as much data as possible. One validation split is itself a little noisy. Cross-validation, in the last section, averages over several splits for a steadier choice.

Complexity knobs and other remedies

Every model family has settings that control flexibility:

  • Trees: max_depth, min_samples_leaf (bigger leaves are smoother).
  • Linear models: the number of features, and regularization strength (C in LogisticRegression, alpha in Ridge).
  • Ensembles: averaging many trees cancels much of their individual variance.

More data also helps: memorizing 50,000 visitors is much harder than memorizing 3,750, so flexible models overfit less as data grows. When the training score is low too, you’re underfitting, and the fix is the opposite: a more flexible model or better features.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Grow a tree until it memorizes

Fit a DecisionTreeClassifier(random_state=42) with no depth limit on the training data.

  • deep_tree: the fitted tree
  • train_acc, test_acc: its accuracy on the training and test sets, rounded to 4 decimals
  • gap: train_acc - test_acc, rounded to 4 decimals
  • n_leaves: the number of leaves, from deep_tree.get_n_leaves()

Compare test_acc with the 0.8472 baseline from the previous lesson.

Need a hint?
  1. DecisionTreeClassifier(random_state=42) has no depth limit by default.
  2. .score(X, y) gives accuracy; call it once with the training data and once with the test data.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

deep_tree = None
train_acc = None
test_acc = None
gap = None
n_leaves = None
print(train_acc, test_acc, gap, n_leaves)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Choose max_depth with a validation set

Pick the tree depth without touching the test set. Split the training data again:

X_fit, X_val, y_fit, y_val = train_test_split(
    X_train, y_train, test_size=0.25, random_state=0, stratify=y_train
)

For each max_depth from 1 to 10, fit DecisionTreeClassifier(max_depth=depth, random_state=42) on the fit set and record its accuracy on the fit set and on the validation set.

  • results: a DataFrame with columns depth, fit_acc, val_acc (one row per depth)
  • best_depth: the depth with the highest val_acc, as an integer
  • final_model: a tree with max_depth=best_depth and random_state=42, refit on all of

X_train, y_train

  • test_acc: final_model's accuracy on the test set, rounded to 4 decimals
Need a hint?
  1. Inside the loop, append a dict per depth: rows.append({"depth": depth, "fit_acc": ..., "val_acc": ...}), then pd.DataFrame(rows).
  2. results["val_acc"].idxmax() gives the row label of the best score; use .loc to read its depth.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

rows = []
# TODO: split X_train into fit/validation sets, then loop over depths 1..10

results = None
best_depth = None
final_model = None
test_acc = None
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status