Overfitting: why the training score flatters
Grow a tree split by split, watch training accuracy climb while new-data accuracy stalls, and learn to spot overfitting on a real run.
What runs in CodeSplash
- Decision tree (CART) Verified in Python and R
You will be able to
- Describe overfitting as learning noise that doesn't repeat in new data
- Read the gap between training and held-out scores
- Turn on the training-row score and read the Diagnostics verdict
Read first
Noise looks like signal
ReadEvery dataset mixes pattern with accident. A flexible model can't tell them apart from the training rows alone: it fits both.
OverfittingOverfittingA model that learned noise in its training data, so it predicts new data worse than its fit suggests. is what happens when a model fits accidents that won't repeat. Training error keeps falling. Error on new rows stops falling, then rises.
The cure starts with measuring it, so you need both numbers.
Grow a tree
ExploreRaise Splits made one at a time and watch the two accuracies. Each split draws one more line, and the boxes get smaller.
DExplorable · Grow a decision tree
How does a tree choose its splits, and when should it stop?
Training accuracy keeps rising with every split. After how many splits will accuracy on new data stop improving?
Data
Split criterion
- 1x₂ ≤ 0.03120 rowsimpurity −0.254
- 2x₁ ≤ 1.5777 rowsimpurity −0.126
- 3x₂ ≤ 0.4266 rowsimpurity −0.012
Commit your prediction above to see the result
Make your prediction to see the result.
Now press split all the way down. Then raise Smallest leaf: a leaf must hold more rows, so the tree can't chase single points. That's a brake on flexibility.
Will a simpler tree do worse?
PredictPredict first
Predicting diabetes. Tree A is up to six levels deep and uses all seven measurements. Tree B is up to three levels deep and uses only glucose, BMI and age. Which has the better cross-validated AUC?
Reveal
The shallow tree. Tree A scores 0.777 and tree B 0.830, and on held-back rows they get 0.708 and 0.754. With 426 training rows, the extra depth mostly learned accidents. Tree B also used balanced class weights and 3 folds, so read this as a direction, not a precise gap.
The gap is the signal
ReadCompare the two scores on one run:
| Training | Held-out | Reading |
|---|---|---|
| Very good | Much worse | Overfitting: reduce flexibility or add rows |
| Poor | About the same | Underfitting: the model is too simple |
| Good | Close | Healthy |
A small gap is normal. What you act on is a large gap that persists as you add rows.
Check your understanding
CheckpointCheck yourself
A model has a training AUC of 0.99 and a cross-validated AUC of 0.74. What's the most likely reading?
Show the answer
Answer: a
A big gap with a very high training score is the signature. Try a smaller model, stronger regularization or more rows.
Check yourself
Which change would make a decision tree overfit more?
Show the answer
Answer: d
The first three limit how finely the tree can cut the data. A random column and unlimited depth give it more chances to find accidental splits.
Check yourself
Training and held-out RMSE are both about the same as the baseline's. What should you try first?
Show the answer
Answer: c
The model isn't even fitting its training rows. More regularization would make it worse.
See it on your run
In the appOpen a run and go to Diagnostics. Under Learning curve, press Compute. It re-fits on growing shares of each fold's training rows and compares the training and validation scores. The banner gives a verdict such as Overfitting (variance) or Underfitting (bias).
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
for depth in [2, 4, 8, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=1)
train = roc_auc_score(y, tree.fit(X, y).predict_proba(X)[:, 1])
held = roc_auc_score(y, cross_val_predict(tree, X, y, cv=cv, method="predict_proba")[:, 1])
print(depth, round(train, 3), round(held, 3))library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
auc <- function(y, p) as.numeric(pROC::auc(y, p, quiet = TRUE))
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
for (depth in c(2, 4, 8, 20)) {
ctl <- rpart.control(maxdepth = depth, cp = 0, minsplit = 2)
p <- numeric(nrow(df))
for (k in 1:5) {
fit <- rpart(type ~ ., df[fold != k, ], control = ctl)
p[fold == k] <- predict(fit, df[fold == k, ])[, "Yes"]
}
whole <- rpart(type ~ ., df, control = ctl)
cat(depth, round(auc(df$type, predict(whole)[, "Yes"]), 3), round(auc(df$type, p), 3), "\n")
}Recap
Recap- Overfitting means fitting accidents. Training scores can't see it.
- Read training and held-out scores side by side: the gap is the evidence.
- Limit flexibility or add rows when the gap is large, and add flexibility when both scores are poor.
Concepts in this lesson