Sub topic 14
Limitations of single trees
This chapter assumes you can fit and score a scikit-learn tree, and that you know what overfitting, cross-validation, and pruning mean from the earlier chapters. A single tree is easy to read and quick to train. It also has structural weaknesses that tuning only partly removes. Knowing them tells you when a tree is the right tool and when you should move to an ensemble.
Summary of the weaknesses
| Limitation | Cause | Typical symptom | Partial remedy |
|---|---|---|---|
| High variance | Greedy splits chosen from small samples | Different structure after small data changes | Pruning, ensembles |
| Axis-aligned boundaries | Each split tests one feature | Staircase fits to diagonal boundaries | Feature engineering, oblique trees, ensembles |
| Piecewise-constant output | Each leaf stores one value | No extrapolation, jagged regression curves | Linear models, boosting with other bases |
| Greedy suboptimality | Best split now, not best tree overall | Missed interactions such as XOR | Deeper trees, ensembles |
| Biased feature choice | More candidate thresholds means more chances to look good | High-cardinality features dominate | Permutation importance, held-out checks |
| Class imbalance | Impurity is dominated by the majority class | Minority class swallowed by large leaves | Class weights, resampling, suitable metrics |
Instability: high variance
Every split depends on the training samples that reach its node. Near the root there are many samples, so the splits are fairly stable. Deeper down, a node may hold a few dozen points. There, moving a single point can change which threshold wins. A different winning split changes all the splits below it, because the children are built from different subsets.
So a tree's predictions can change a lot when the training data changes a little. This is high variance. It is the same overfitting you saw in the earlier chapters, seen from another angle. You can measure it by refitting on bootstrap resamples, which are samples drawn with replacement from the training set:
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
data = load_iris()
X, y = data.data, data.target
rng = np.random.RandomState(0)
for i in range(5):
idx = rng.choice(len(X), size=len(X), replace=True)
tree = DecisionTreeClassifier(random_state=0).fit(X[idx], y[idx])
root_feature = data.feature_names[tree.tree_.feature[0]]
root_threshold = tree.tree_.threshold[0]
print(f"resample {i}: root splits on {root_feature} <= {root_threshold:.2f}, "
f"{tree.get_n_leaves()} leaves, depth {tree.get_depth()}")On iris the root often splits on a petal measurement, but the threshold, the number of leaves, and the depth change from resample to resample. Several features separate class 0 so cleanly that their split scores tie or nearly tie. A small change in the sample is enough to flip which one wins. On noisier data the root itself changes.
Instability affects interpretation as well as accuracy. If the "rules" change when you retrain next month on slightly newer data, then you should not treat them as stable facts about the world.
Axis-aligned boundaries
A standard tree split has the form feature <= threshold. Every decision boundary is therefore parallel to a coordinate axis. A boundary such as x1 > x2 is a diagonal line. A tree can only approximate it with a staircase of many small rectangles, and it needs more depth the more accurate you want it to be.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
rng = np.random.RandomState(0)
X = rng.uniform(-1, 1, size=(2000, 2))
y = (X[:, 0] > X[:, 1]).astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
plain = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print("raw features, depth 3:", plain.score(X_test, y_test))
def add_difference(A):
return np.column_stack([A, A[:, 0] - A[:, 1]])
engineered = DecisionTreeClassifier(max_depth=1, random_state=0)
engineered.fit(add_difference(X_train), y_train)
print("with x1 - x2, depth 1:", engineered.score(add_difference(X_test), y_test))The first score is clearly below 1.0, because a depth-3 staircase cannot follow the diagonal. The second is close to 1.0 with a single split. Adding a derived feature that matches the real structure of the problem fixes the weakness here. In general you do not know the right combinations ahead of time. Oblique trees, which split on linear combinations of features, exist but are not part of scikit-learn's standard tree classes.
Piecewise-constant predictions and no extrapolation
A regression tree predicts the mean target of the training samples in a leaf. Its output is a step function with a finite number of values. Outside the range of the training data, the prediction is the value of the nearest edge leaf and does not follow any trend.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
X = np.arange(0, 10, 0.5).reshape(-1, 1)
y = 2 * X.ravel()
tree = DecisionTreeRegressor(random_state=0).fit(X, y)
line = LinearRegression().fit(X, y)
X_new = np.array([[20.0], [100.0]])
print("tree: ", np.round(tree.predict(X_new), 2)) # [19. 19.]
print("linear:", np.round(line.predict(X_new), 2)) # [ 40. 200.]The training data reach x = 9.5, where y = 19. The tree returns 19 for every larger input. This matters for forecasting, for data that drifts over time, and for any problem where test inputs can fall outside the training range. Random forests and standard gradient boosting built from trees inherit this behavior.
The step shape also makes tree predictions unsmooth. Two inputs that differ by a tiny amount can land in different leaves and get very different predictions.
Greedy search and missed interactions
The tree picks the split with the best immediate impurity decrease. It never looks ahead. This fails when a feature is useful only in combination with another. The classic case is XOR, where the label is 1 when exactly one of two binary features is 1. No single split on either feature reduces impurity, since each feature alone is uncorrelated with the label. The greedy criterion sees no gain and may split on a noise feature, or stop early if a minimum-decrease threshold is set.
from sklearn.tree import DecisionTreeClassifier
X = [[0, 0], [0, 1], [1, 0], [1, 1]] * 25
y = [0, 1, 1, 0] * 25
tree = DecisionTreeClassifier(random_state=0).fit(X, y)
print("depth:", tree.get_depth(), "train accuracy:", tree.score(X, y))A fully grown tree does solve this tiny case, because depth 2 can separate all four cells. But it needs a split with zero gain first. Add a minimum impurity decrease or a depth limit of 1, and the tree gets stuck. With many noise features, a zero-gain first split can also land on the wrong feature. The general lesson is that greedy optimality is local. The best tree overall may begin with a split that looks worthless.
Finding the globally optimal tree is NP-complete, so greedy construction is the practical choice. Deeper trees paper over the problem, but only by taking on the variance described above.
Biased feature selection
Impurity-based splitting favors features that offer many candidate thresholds. A continuous feature or a categorical feature with many levels, such as a user ID, has many ways to split the data. Among many random candidates, one will look good by chance. The tree can then pick an ID-like feature that has no real signal. The same bias inflates its impurity-based importance, as the feature importance chapter explained.
Check this when your data has identifier columns or high-cardinality categories. Drop them, group rare levels, or compare impurity-based importances with permutation importance computed on held-out data.
Class imbalance
Gini and entropy are computed from class proportions across the whole node. If 98% of samples belong to one class, a leaf that predicts the majority class everywhere already has a very low impurity. Splits that isolate small groups of the minority class produce little decrease, so the tree may not make them. The tree reaches high accuracy and still misses most minority cases.
Use class_weight="balanced" to make minority samples count more in the impurity calculation. Judge the model with recall, precision, or PR-AUC rather than accuracy alone. Also set min_samples_leaf with the minority class size in mind. A value that is large relative to the minority class can prevent any leaf from being dominated by it.
How ensembles respond
Ensembles take the weaknesses above as their starting point. The next chapter covers them, so here is only the connection.
- Bagging and random forests average many deep, high-variance trees trained on resampled data. Averaging cancels much of the variance that makes single trees unstable. Averaging many staircases also gives a smoother approximation of a diagonal boundary.
- Boosting builds shallow trees in sequence, each correcting the errors of the earlier ones. This lowers bias and lets the model capture interactions that a single greedy tree misses.
Ensembles do not fix everything. Tree-based ensembles still cannot extrapolate beyond the training range. They also give up the readable rule structure that made a single tree attractive in the first place.
Decision criteria
A single tree is a good choice when you need a model that people can read and audit, when the data are tabular with mixed types, or when you need a fast baseline. It is a poor choice when you need the best predictive accuracy, stable rules across retraining, extrapolation, or smooth responses. In those cases, start with a linear model for extrapolation or an ensemble for accuracy, and keep the tree as an explanatory companion.
Exercise
You fit a DecisionTreeRegressor to monthly sales from 2020 to 2023 and use it to forecast 2025. The forecast is flat and sits at the level of late 2023. Which limitation causes this, and what would you try instead?
Show answer
A regression tree is piecewise constant and cannot extrapolate. For inputs beyond the training range it returns the mean of the nearest edge leaf. Use a model that can represent a trend, such as a linear model, or add a trend term and let a tree model the residuals. A random forest or boosted trees would show the same flat behavior.
Exercise
On a dataset where the true boundary is the diagonal line x1 = x2, a depth-3 tree scores poorly. Give one way to improve it without changing the model type, and say why it works.
Show answer
Add the derived feature x1 - x2. The boundary then becomes a single axis-aligned split on the new feature (threshold near 0), which a depth-1 tree can find.