Sub topic 8
Decision trees and their limits
This chapter assumes you can fit a scikit-learn model inside a pipeline, read cross-validation scores, and know what overfitting means. It also assumes you have seen the baseline and linear-model chapters. A single decision tree is rarely the model you ship, but random forests and gradient boosting are built from trees. If you know how one tree fails, you can see why those ensembles work.
How a tree makes a prediction
A decision tree is a sequence of yes/no questions about one feature at a time. Each question sends a row left or right. A row ends in a leaf, and the leaf returns the majority class (or class probabilities) for classification, or the mean target for regression.
The tree is built greedily. At each node, the algorithm tries every feature and every candidate threshold. It keeps the split that most reduces impurity in the child nodes, weighted by how many rows go to each child. For classification, the default impurity is Gini: 1 - sum(p_k^2), where p_k is the share of class k in the node. A pure node scores 0. For regression, the default is squared error around the node mean.
"Greedy" means each split is chosen for its immediate gain, without looking ahead. The final tree is therefore not guaranteed to be the best tree of its size.
What trees do well
- No scaling needed. Splits depend only on the order of values, so standardizing a column changes nothing. Skip
StandardScalerfor a tree-only pipeline. - Interactions come built in. A second split below the first lets the tree represent "age over 45 and city is a" without you creating a feature. A plain logistic regression cannot represent XOR-style patterns unless you add the interaction yourself.
- Non-linear effects are free. A tree can learn that risk rises, plateaus, then drops with a feature.
- Robust to outliers in features. An extreme income value lands in the same leaf as the next-largest values.
- Readable at small depth. A depth-3 tree can be printed and checked by a domain expert.
Overfitting: a tree can memorize
With no limits, a tree keeps splitting until every leaf is pure. Training accuracy then reaches 100% unless two rows have identical features and different labels. The tree has memorized the training set, noise included. The code below sweeps max_depth on the synthetic table from the pipeline example and compares training and validation AUC.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
# No scaler: trees do not need one.
preprocess = ColumnTransformer([
("num", SimpleImputer(strategy="median"), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for depth in [1, 2, 3, 5, 8, None]:
model = make_pipeline(
preprocess, 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"valid={res['test_score'].mean():.3f}"
)Expect depth 1 to underfit, because one split cannot express an XOR. Depth 2 should capture the true structure. Beyond that, training AUC stays at or near 1.0 while validation AUC stops improving or slips, because extra splits only fit noise (here, the random income column). A growing gap between the two columns is the signature of overfitting. Always report the validation number, never the training one.
Controlling tree size
Most hyperparameters limit how far the tree can grow. They are listed here in the order I usually reach for them.
| Parameter | Effect | Practical note |
|---|---|---|
| `max_depth` | Caps the number of questions on any path | Simple and easy to explain. Try 3 to 10. |
| `min_samples_leaf` | Each leaf must hold at least this many rows | Often the most effective regularizer. Larger values give smoother predictions. |
| `min_samples_split` | A node needs this many rows before it may split | Weaker than `min_samples_leaf` because it still allows tiny leaves. |
| `max_leaf_nodes` | Caps the total leaf count | Grows the best-first, so effort goes to the useful splits. |
| `ccp_alpha` | Prunes branches whose gain does not justify their complexity | Use `cost_complexity_pruning_path` to see candidate values. |
| `class_weight` | Reweights classes in the impurity calculation | Helps with imbalance, but does not replace choosing a suitable metric. |
Tune these inside cross-validation, never against the test set. The tuning chapter covers how to do that without contaminating your estimate.
The limits of a single tree
High variance
A small change in the training data can change the top split, and then everything below it. Two trees fit on two bootstrap samples of the same table can look unrelated while scoring similarly. This instability is why single trees often trail other models on the same folds. Averaging many trees reduces the variance, which is the idea behind random forests, covered in the next chapter.
Axis-aligned splits
Every question involves one feature. If the true boundary is diagonal, such as "income greater than twice the debt", the tree approximates it with a staircase of many splits. That costs depth, and each extra split leaves fewer rows for the estimate. A linear model, or a hand-made ratio feature, handles this case in one step.
No extrapolation
A tree predicts a value seen in training leaves. Outside the training range, it repeats the value of its outermost leaf.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
x_train = rng.uniform(0, 10, 200).reshape(-1, 1)
y_train = 2 * x_train.ravel() + rng.normal(0, 1, 200)
x_new = np.array([[5.0], [15.0], [30.0]])
tree = DecisionTreeRegressor(min_samples_leaf=5, random_state=0)
tree.fit(x_train, y_train)
linear = LinearRegression().fit(x_train, y_train)
print("tree: ", tree.predict(x_new).round(1))
print("linear:", linear.predict(x_new).round(1))The true values at 5, 15 and 30 are roughly 10, 30 and 60. The linear model follows the trend. The tree returns about 10 at 5, then about 20 at both 15 and 30, the mean of its last leaf. If your data drifts upward over time (prices, counts, sensor readings), tree-based models, including forests and boosting, will lag behind it.
Piecewise-constant predictions
A regression tree outputs a step function. Predictions are the same for every row in a leaf, so ranking within a leaf is impossible. For AUC, this means many ties, since a shallow tree produces only a few distinct scores. Probabilities from a tree are also poorly calibrated: a leaf with 3 of 3 positives reports 100%.
Biased impurity importance
feature_importances_ sums impurity reductions per feature. Features with many distinct values, such as IDs or continuous noise, get more chances to find a lucky split, and they are rated higher than they deserve. It is also computed on training data. Prefer sklearn.inspection.permutation_importance on held-out data when you need to report which features matter.
Categorical features
Scikit-learn trees expect numeric input, so categories need encoding. One-hot encoding a column with hundreds of levels gives sparse binary features, and each split can isolate only one level. The tree then needs many splits to group levels. Ordinal encoding imposes an arbitrary order that the tree may split in unhelpful ways. Recent versions (1.3 and later) let trees handle NaN natively, so imputation is optional for them, but encoding is still your job.
When a single tree is the right choice
Use a single, shallow tree when:
- the model must be inspected line by line by non-technical reviewers;
- you need a quick check for interactions before building features;
- you want a stricter baseline than the dummy model, to see whether any non-linear structure is present.
In nearly every other case, treat the single tree as a stepping stone. If a depth-4 tree beats your logistic regression by a clear margin on the same folds, that suggests non-linear or interaction structure. This is a good reason to try forests and boosting next.
Exercise
A regression tree is trained on house prices from 2015 to 2020 and used to predict prices in 2024, when prices are well above anything in the training set. Its predictions look too low and cluster at one value. What causes this, and what two changes could help?
Show answer
A tree predicts the mean of the training rows in a leaf, so for inputs beyond the training range it returns the value of its outermost leaf and cannot extrapolate an upward trend. Two options are to use a model that can extrapolate, such as a linear model, or to predict a detrended target (for example, price relative to a market index) and add the trend back afterward. Retraining on recent data also reduces the gap.
Exercise
In the depth sweep, training AUC is 1.0 at maxdepth=None while validation AUC is lower than at maxdepth=2. Name the problem, and name two parameters you could set to reduce it.
Show answer
This is overfitting: the tree memorized noise in the training folds. Setting maxdepth (for example, 2 to 4) or minsamplesleaf (for example, 10 or more) limits how finely it can split. ccpalpha and maxleafnodes also work.