Sub topic 8
Decision trees and their limits
This chapter assumes you can fit scikit-learn estimators, use cross-validation, and read a train versus validation score gap. It covers how a single tree makes predictions, how to control its size, and why you rarely ship one alone.
How a tree predicts
A decision tree is a model that asks a series of yes/no questions about one column at a time. Each question is a split, such as age <= 45. Training picks, at each node, the split that makes the resulting groups most pure. For classification, purity is usually measured with Gini impurity or entropy. For regression, it is the variance of the target. A leaf is a node with no further split. It predicts the majority class, or the mean target, of the training rows that reach it.
Trees suit tabular data for several reasons:
- They need no feature scaling.
- They capture interactions, such as "age matters only in city a", without you adding terms.
- They handle non-linear effects.
- You can read them.
Depth controls overfitting
An unconstrained tree keeps splitting until every leaf is pure. It then memorizes the training set, including noise. The fix is to limit its size with max_depth, min_samples_leaf, or ccp_alpha (cost-complexity pruning).
from sklearn.datasets import make_classification
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=500, n_features=10, n_informative=4, flip_y=0.1, random_state=0
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for depth in [2, 4, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=0)
res = cross_validate(
model, X, y, cv=cv, scoring="roc_auc", return_train_score=True
)
print(
f"max_depth={depth}: "
f"train={res['train_score'].mean():.3f} "
f"validation={res['test_score'].mean():.3f}"
)With max_depth=None, the training AUC is 1.000 because the tree fits every training row. The validation AUC is much lower. A large gap between the two scores is the signature of overfitting. A shallow tree has a smaller gap, but if both scores are low, it underfits.
Limits to know
| Limit | What happens | Typical symptom |
|---|---|---|
| High variance | A small change in the training data can produce a very different tree. | Scores vary widely across folds. |
| Axis-aligned splits | Each split uses one column, so a diagonal boundary needs many steps. | A linear model beats a deep tree on smooth relationships. |
| No extrapolation | A leaf predicts a value seen in training, so predictions are flat outside the training range. | Regression forecasts that plateau. |
| Biased split choice | Columns with many distinct values (IDs, continuous measurements) get more chances to produce a good-looking split. | An ID-like column ranks as important. |
| Step-shaped output | Predictions come from a few leaves, so probabilities take few distinct values. | Coarse ranking, poor calibration. |
Where a tree fits in model selection
A shallow tree is a useful second baseline after the dummy model. It is cheap and readable, and it shows whether interactions matter. If a depth-3 tree clearly beats logistic regression, the relationship is probably non-linear or involves interactions. That is a reason to try ensembles.
Random forests and gradient-boosted trees address the variance problem by combining many trees. The next chapters cover them. Keep a single tree as the final model only when you must show the exact decision rules and a small accuracy loss is acceptable.
Exercise
A decision tree with no depth limit scores AUC 1.000 on the training folds and 0.74 on the validation folds. Name the problem and two hyperparameters that would help.
Show answer
The tree is overfitting: it memorized the training rows, including noise. Set max_depth to a small value or raise min_samples_leaf. ccp_alpha for pruning also works. Check that the training and validation scores move closer together without the validation score dropping.
Exercise
You train a tree regressor on house prices from 2015 to 2020 and use it to predict 2024 prices. Why will it likely under-predict, and what kind of model could behave differently?
Show answer
A tree cannot extrapolate. Each leaf returns an average of training targets, so predictions stay within the range seen in training. A linear model can continue a trend beyond the training range, although it may be wrong if the trend does not hold.