Better models: overfitting, ensembles and validation
How do you know a model will work on tomorrow's data? This module covers the tools practitioners use to build models that generalise.
Learning objectives
- Diagnose overfitting from training vs test scores
- Explain random forests and gradient boosting
- Compare models with k-fold cross-validation
- Tune hyperparameters with grid search
- Use pipelines to prevent leakage
- Read a learning curve to decide whether more data would help
- Describe what tabular foundation models are and when to consider them
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
"tenure_months": rng.integers(1, 60, n),
"monthly_spend": rng.normal(40, 15, n).clip(5, 120).round(2),
"support_tickets": rng.poisson(1.2, n),
"on_promo": rng.integers(0, 2, n),
"region": rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
- 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
+ rng.normal(0, 40, n)).round(2)
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
features = ["tenure_months", "monthly_spend", "support_tickets", "on_promo"]
X, y = customers[features], customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score4.1 Overfitting, again
A model that memorises its training data performs brilliantly on it and poorly on new data. Compare training and test scores: a big gap signals overfitting.
for depth in [2, 4, 8, 16, None]:
t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
print(f"depth {str(depth):4} train {t.score(X_train, y_train):.3f} test {t.score(X_test, y_test):.3f}")
Unlimited depth reaches near-perfect training accuracy while test accuracy drops — classic overfitting.
The opposite problem is underfitting: a model too simple to capture the pattern scores poorly on both training and test data. The aim is the middle ground — flexible enough to learn the real pattern, constrained enough not to learn the noise.
4.2 Ensembles: many models are better than one
| Model | Idea | Strengths |
|---|---|---|
| Random forest | Many trees, each trained on a random sample of rows and features; they vote | Robust, little tuning, resists overfitting |
| Gradient boosting | Trees built one after another, each correcting the previous ones' errors | Often the most accurate on tabular data |
For structured, tabular business data, tree ensembles are frequently the best-performing choice — often outperforming deep learning.
Why does combining help? One deep tree makes confident, quirky mistakes that depend on exactly which rows it saw. A hundred trees, each shown a slightly different sample, make different mistakes, and averaging cancels much of that out. Boosting works differently: each small tree concentrates on the customers the previous trees got wrong.
4.3 Cross-validation
A single train/test split can be lucky or unlucky. k-fold cross-validation splits the training data into k parts, trains on k−1 and validates on the remaining one, k times, and averages the scores. Use it to compare models and settings; keep the test set for the final check.
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
models = {
"logistic": LogisticRegression(max_iter=1000),
"tree (depth 4)": DecisionTreeClassifier(max_depth=4, random_state=0),
"random forest": RandomForestClassifier(n_estimators=100, random_state=0),
"gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
for name, m in models.items():
scores = cross_val_score(m, X_train, y_train, cv=5, scoring="roc_auc")
print(f"{name:18} AUC {scores.mean():.3f} ± {scores.std():.3f}")
On this dataset the hidden pattern is close to linear, so logistic regression may do as well as the ensembles — a useful reminder that complex isn't always better.
Look at the ± figures too. If two models differ by 0.005 and the spread across folds is 0.02, you can't say one is better; pick the simpler or cheaper one.
4.4 Hyperparameter tuning
Hyperparameters are settings you choose before training (tree depth, number of trees, learning rate). Search over them with cross-validation. (This cell trains 24 small forests, so give it a few seconds.)
from sklearn.model_selection import GridSearchCV
grid = GridSearchCV(RandomForestClassifier(n_estimators=50, random_state=0),
{"max_depth": [4, 8, None], "min_samples_leaf": [1, 10]},
cv=4, scoring="roc_auc")
grid.fit(X_train, y_train)
print(grid.best_params_, round(grid.best_score_, 3))
print("Test AUC:", round(roc_auc_score(y_test, grid.predict_proba(X_test)[:, 1]), 3))
On your own computer, add n_jobs=-1 to use every processor core, and search a wider grid. For large searches, RandomizedSearchCV tries a random sample of combinations and usually finds something nearly as good in a fraction of the time.
4.5 Pipelines keep it honest
Put preprocessing (imputation, scaling, encoding) and the model in one pipeline, so cross-validation refits preprocessing within each fold — preventing leakage (see Data Quality, Module 5).
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
print(cross_val_score(pipe, X_train, y_train, cv=5, scoring="roc_auc").mean().round(3))
4.6 Would more data help?
Before asking for more data (which is slow and expensive), check whether the model is still improving as it sees more. Train on growing slices of the training set and watch the score on held-out data — a learning curve.
Python · a learning curvefrom sklearn.model_selection import learning_curve
import matplotlib.pyplot as plt
sizes, train_scores, val_scores = learning_curve(
LogisticRegression(max_iter=1000), X_train, y_train,
train_sizes=[50, 100, 200, 400, 800, 1280], cv=5, scoring="roc_auc")
for s, v in zip(sizes, val_scores.mean(axis=1)):
print(f"{s:5} rows validation AUC {v:.3f}")
plt.plot(sizes, train_scores.mean(axis=1), "o-", label="training")
plt.plot(sizes, val_scores.mean(axis=1), "o-", label="validation")
plt.xlabel("Training rows"); plt.ylabel("AUC"); plt.legend()
plt.show()
Here the validation score is flat almost from the start: the pattern is simple, and logistic regression has learned it within the first hundred rows. The training line falls towards it, because a handful of rows is easy to fit perfectly and a thousand is not. Once the validation curve is flat, more rows of the same kind won't help; better features (new information about each customer) are the way forward.
4.7 What's new: tabular foundation models
For twenty years the advice for tables of business data has been "start simple, then try gradient boosting". A newer family of models is starting to challenge that: tabular foundation models, such as TabPFN. In the same way that a large language model is pretrained on text, these are pretrained on millions of artificial tables. Given your training rows and the rows you want predictions for, they predict in a single pass, with no training step and no tuning.
Their authors report results that beat tuned gradient boosting on standard benchmarks for small and medium-sized tables, and they use the familiar scikit-learn pattern:
Python · for Colab or your own computer (too large to run in the browser)# pip install tabpfn
from tabpfn import TabPFNClassifier
clf = TabPFNClassifier()
clf.fit(X_train, y_train) # no real training: it just stores the rows
proba = clf.predict_proba(X_test)[:, 1]
Treat them as one more candidate to compare, not a replacement for the workflow in this course:
- They are large neural networks: slower and costlier per prediction than a small tree model, and best with a GPU.
- There are limits on table size, and licence terms to check before commercial use.
- They are harder to explain than a linear model or a shallow tree.
- Everything else still applies: a baseline, an untouched test set, the right metric, checks by group.
Use GridSearchCV with cv=3 to tune a HistGradientBoostingClassifier over learning_rate (0.03, 0.1) and max_depth (2, 4). Which settings win, and does the tuned model beat logistic regression's cross-validated AUC?
Your turn# Write your code here, then press RunShow a solution
g = GridSearchCV(HistGradientBoostingClassifier(random_state=0),
{"learning_rate": [0.03, 0.1], "max_depth": [2, 4]}, cv=3, scoring="roc_auc")
g.fit(X_train, y_train)
print(g.best_params_, round(g.best_score_, 3))
print("Logistic:", cross_val_score(LogisticRegression(max_iter=1000), X_train, y_train, cv=3, scoring="roc_auc").mean().round(3))
# Shallow trees win, and the tuned model still doesn't beat logistic regression here.A colleague adds a feature refund_issued and the AUC jumps to 0.99. Refunds are issued when a customer cancels. Simulate it: add a column that equals churned for 95% of customers, retrain, and look at the score. Why must this feature be removed?
Your turnleaky = customers[features].copy()
flip = np.random.default_rng(1).random(len(customers)) < 0.05 # 5% of rows disagree
leaky["refund_issued"] = np.where(flip, 1 - customers["churned"], customers["churned"])
# Cross-validate a model on leaky, then press RunShow a solution
leaky = customers[features].copy()
flip = np.random.default_rng(1).random(len(customers)) < 0.05
leaky["refund_issued"] = np.where(flip, 1 - customers["churned"], customers["churned"])
print(cross_val_score(LogisticRegression(max_iter=1000), leaky, customers["churned"], cv=5, scoring="roc_auc").mean().round(3))
# Near-perfect, and useless: the refund happens AFTER the customer leaves,
# so it won't exist at the moment you need the prediction. That is data leakage.Key takeaways
- A large train–test gap signals overfitting.
- Random forests average many trees; boosting builds trees that correct errors.
- Cross-validation gives more reliable comparisons than one split.
- Tune hyperparameters with cross-validation; test once at the end.
- Pipelines refit preprocessing within each fold.
- A flat learning curve means more rows won't help; look for better features.
- Tabular foundation models predict without training; treat them as one more candidate to test.