Regression Trees and Pruning
Trees predict numbers too. A regression tree asks the same kind of yes/no questions as a classification tree, but each leaf predicts the mean target of its training examples, and splits are chosen to reduce squared error instead of Gini impurity. Regression trees are the weak learners inside gradient boosting, so it pays to know them well. This lesson also covers pruning: growing a large tree and then cutting it back, the original CART recipe for choosing a tree's size.
Splitting by squared error
For a node with targets the best constant prediction is the mean , and the node's impurity is its sum of squared errors . A split is chosen to minimise , which is the same as maximising the drop in variance. scikit-learn calls this criterion="squared_error"; "absolute_error" (leaf median) is more robust to outliers, "poisson" suits counts.
The data below is a step function, 1 for , 4 for and 2 above, plus noise:
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 10, 80))
y = np.where(x < 3, 1.0, np.where(x < 7, 4.0, 2.0)) + rng.normal(scale=0.5, size=80)
def best_stump(x, y):
"""The threshold that most reduces the sum of squared errors (x sorted)."""
best = (np.inf, None)
for i in range(1, len(x)):
if x[i] == x[i - 1]:
continue
l, r = y[:i], y[i:]
sse = ((l - l.mean()) ** 2).sum() + ((r - r.mean()) ** 2).sum()
if sse < best[0]:
best = (sse, (x[i - 1] + x[i]) / 2)
return best
sse, t = best_stump(x, y)
print("total SSE before the split:", round(((y - y.mean()) ** 2).sum(), 2))
print("best first split: x <=", round(t, 3), " SSE after:", round(sse, 2))
print("leaf means:", round(y[x <= t].mean(), 3), round(y[x > t].mean(), 3))
sk = DecisionTreeRegressor(max_depth=1).fit(x[:, None], y)
print("sklearn stump: x <=", round(sk.tree_.threshold[0], 3), " leaf values:", sk.tree_.value[1:, 0, 0].round(3))
for depth in [1, 2, 3, 8]:
m = DecisionTreeRegressor(max_depth=depth, random_state=0).fit(x[:, None], y)
print(f"depth {depth}: {m.get_n_leaves():2d} leaves, training MSE {np.mean((m.predict(x[:, None]) - y) ** 2):.3f}")total SSE before the split: 149.14
best first split: x <= 3.05 SSE after: 73.23
leaf means: 1.012 3.194
sklearn stump: x <= 3.05 leaf values: [1.012 3.194]
depth 1: 2 leaves, training MSE 0.915
depth 2: 4 leaves, training MSE 0.206
depth 3: 8 leaves, training MSE 0.178
depth 8: 57 leaves, training MSE 0.026
The first split lands at 3.05, next to the true jump at 3, and halves the SSE; the leaf values are the means on each side and match scikit-learn's stump. At depth 2 the tree has found both jumps and the training MSE (0.206) is close to the noise variance . Everything beyond that fits noise: at depth 8 the tree has 57 leaves for 80 points and a training MSE of 0.026, far below the noise level, a sure sign of overfitting.
Cost-complexity pruning
Stopping rules like max_depth are blunt: a split that looks useless may enable a very useful split below it. CART's answer is to grow a large tree and then prune it, scoring every subtree by its error plus a price per leaf:
where is the total training impurity of the leaves (for regression scikit-learn uses the weighted mean squared error) and the number of leaves. For the full tree is best; as grows, the subtree whose removal costs least error per leaf saved (the "weakest link") is collapsed first. This gives a nested sequence of subtrees, one per critical value of , and cross-validation picks the . The criterion has the shape of every regularised objective in this course: fit plus a complexity penalty (Empirical Risk Minimization, Model Selection).
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.tree import DecisionTreeRegressor
X, y = load_diabetes(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
full = DecisionTreeRegressor(random_state=0).fit(X_tr, y_tr)
print("unpruned: leaves", full.get_n_leaves(), " train R^2", round(full.score(X_tr, y_tr), 3), " test R^2", round(full.score(X_te, y_te), 3))
path = full.cost_complexity_pruning_path(X_tr, y_tr) # every alpha where the pruned tree changes
alphas = path.ccp_alphas[:-1]
print("candidate alphas:", len(alphas))
search = GridSearchCV(DecisionTreeRegressor(random_state=0), {"ccp_alpha": alphas[::5]},
cv=KFold(5, shuffle=True, random_state=0)).fit(X_tr, y_tr)
best = search.best_estimator_
print("chosen alpha:", round(search.best_params_["ccp_alpha"], 1))
print("pruned: leaves", best.get_n_leaves(), " train R^2", round(best.score(X_tr, y_tr), 3), " test R^2", round(best.score(X_te, y_te), 3))
d4 = DecisionTreeRegressor(max_depth=3, random_state=0).fit(X_tr, y_tr)
print("depth 3: leaves", d4.get_n_leaves(), " train R^2", round(d4.score(X_tr, y_tr), 3), " test R^2", round(d4.score(X_te, y_te), 3))unpruned: leaves 318 train R^2 1.0 test R^2 -0.182
candidate alphas: 292
chosen alpha: 456.9
pruned: leaves 3 train R^2 0.423 test R^2 0.206
depth 3: leaves 8 train R^2 0.578 test R^2 0.087
The unpruned tree has a leaf for almost every one of the 331 training patients, a perfect training fit and a test of : worse than predicting the mean. Pruning with chosen by 5-fold cross-validation on the training part (every fifth candidate, to keep the example fast) keeps just 3 leaves and reaches 0.206 on the test set, better than a depth-3 tree. Yet even the pruned tree stays well below linear regression's 0.359 on the same split: the diabetes signal is mostly additive and smooth, which piecewise-constant boxes approximate poorly. A forest or boosted ensemble of trees closes much of that gap.
Hyperparameters, strengths, weaknesses
The hyperparameters are those of classification trees, with criterion among "squared_error", "friedman_mse", "absolute_error" and "poisson", and ccp_alpha for pruning. Regression trees model thresholds, interactions and nonlinearity with no feature engineering. Their predictions are step functions, they cannot extrapolate (beyond the data the prediction is the last leaf's mean), and a single tree has high variance. Use one alone for interpretable rules; use many in a forest or in boosting for accuracy.
Pitfalls
- Extrapolating a trend. A tree trained on house prices up to 2024 predicts 2030 prices at the 2024 level.
- Pruning on the test set. Choosing by test score makes the test score optimistic; use cross-validation on the training data, as above.
- Comparing
ccp_alphaacross data sets. It is on the scale of the impurity (squared target units).
Practice
- A leaf holds the targets 2, 4 and 9. What does it predict with
squared_errorand withabsolute_error?
Answer
The mean, 5, for squared error; the median, 4, for absolute error. The median ignores how far the 9 is from the rest.
- Why can a tree that is pruned back to 3 leaves beat a depth-3 tree with 8 leaves on the test set?
Answer
The depth-3 tree spends its leaves wherever the greedy search found any training improvement, including noise; pruning removes the leaves whose error reduction is smallest per leaf and keeps only the splits that cross-validation says generalise. Fewer, better-chosen leaves have less variance.
Test yourself
What does a leaf of a regression tree trained with squared error predict?
- The median of its training targets
- The mean of its training targets
- The most common target
- A linear fit of its targets
In , what happens as grows?
- The tree grows deeper
- Leaves become more expensive, so smaller subtrees win
- The training error drops
- Nothing; only affects classification
A regression tree is trained on temperatures between 0 and 30 degrees. What does it predict at 40 degrees?
- A linear extrapolation
- The value of the leaf that contains the largest training temperatures
- Zero
- An error