Sub topic 11
Regression trees
A regression tree predicts a number instead of a class. It uses the same machinery as the classification trees from earlier chapters: greedy recursive partitioning, threshold search, stopping rules, and pruning. Only two parts change. The leaf prediction becomes an average, and the impurity measure becomes a measure of spread in the target.
This chapter assumes you know how a classification tree picks a split using impurity and weighted child impurity. It also assumes basic Python, NumPy, and the scikit-learn fit/predict pattern.
What changes from classification
In a classification tree, a leaf predicts the majority class and a node is "pure" when all its samples share a label. A regression target is continuous, so no two samples usually share the same value and "pure" needs a new definition. A node is good if its target values are close together. The node's prediction is then their mean.
| Part of the algorithm | Classification tree | Regression tree |
|---|---|---|
| Leaf prediction | Majority class (or class proportions) | Mean of the training targets in the leaf |
| Node impurity | Gini or entropy | Variance (mean squared error around the node mean) |
| Split score | Weighted child impurity | Weighted child variance |
| Split gain | Impurity decrease | Variance reduction |
| Default scikit-learn criterion | `gini` | `squared_error` |
| Score from `.score()` | Accuracy | R² |
The tree structure is the same: a root, internal nodes that test one feature against one threshold, and leaves.
The mean as the leaf prediction
Why the mean? Suppose a leaf contains the target values y₁ … yₙ and must output one constant c. Under squared error, the total loss is the sum of (yᵢ − c)². This sum is smallest when c is the mean of the yᵢ. So if you measure error as squared error, the mean is the best constant a leaf can predict.
This also explains the impurity measure. The loss left in a leaf when it predicts its mean is its variance (times n). Variance is therefore the regression analogue of Gini impurity. It is zero when every target in the node is identical, and it grows as the targets spread out.
Variance reduction
For a candidate split of a node into left and right children, the score is the weighted average of the child variances:
weighted variance = (nleft · Var(left) + nright · Var(right)) / n
The variance reduction is Var(parent) minus this weighted variance. The tree picks the feature and threshold with the largest reduction, which is the same as the smallest weighted child variance. This mirrors the weighted impurity decrease you used for classification.
A worked example
Take six points, with a clear jump in the target between x = 3 and x = 10:
- x = 1, 2, 3, 10, 11, 12
- y = 1.0, 1.2, 0.8, 5.0, 5.2, 4.8
The parent mean is 18 / 6 = 3.0. The squared deviations are 4, 3.24, 4.84, 4, 4.84, 3.24, which sum to 24.16. The parent variance is 24.16 / 6 ≈ 4.0267.
Now try the threshold 6.5, the midpoint between 3 and 10:
- Left child: y = 1.0, 1.2, 0.8. The mean is 1.0 and the variance is 0.08 / 3 ≈ 0.0267.
- Right child: y = 5.0, 5.2, 4.8. The mean is 5.0 and the variance is also ≈ 0.0267.
- Weighted variance: (3 · 0.0267 + 3 · 0.0267) / 6 ≈ 0.0267.
- Variance reduction: 4.0267 − 0.0267 = 4.0.
The split search in code
The split search is the same scan you saw for Gini. Sort the feature values, test the midpoint between each pair of distinct neighbors, and keep the lowest weighted impurity. Only the impurity function changes.
def variance(ys):
n = len(ys)
if n == 0:
return 0.0
mean = sum(ys) / n
return sum((y - mean) ** 2 for y in ys) / n
def best_threshold_reg(xs, ys):
pairs = sorted(zip(xs, ys))
best = (None, float("inf"))
for i in range(1, len(pairs)):
if pairs[i - 1][0] == pairs[i][0]:
continue
t = (pairs[i - 1][0] + pairs[i][0]) / 2
left = [y for x, y in pairs if x <= t]
right = [y for x, y in pairs if x > t]
score = (len(left) * variance(left) + len(right) * variance(right)) / len(pairs)
if score < best[1]:
best = (t, score)
return best
xs = [1, 2, 3, 10, 11, 12]
ys = [1.0, 1.2, 0.8, 5.0, 5.2, 4.8]
t, score = best_threshold_reg(xs, ys)
print(t, round(score, 4), round(variance(ys) - score, 4)) # 6.5 0.0267 4.0This version recomputes each child from scratch, so it costs O(n²) per feature. Real implementations sort once and update running sums of y and y² as the threshold moves, which makes the scan O(n) after sorting.
Other split criteria
Squared error is the default, but scikit-learn's DecisionTreeRegressor offers more through the criterion parameter.
squared_error: variance reduction. Leaves predict the mean.friedman_mse: squared error with an improvement score from gradient boosting. It sometimes picks slightly different splits.absolute_error: minimizes mean absolute error. Leaves predict the median, which makes the tree less sensitive to outliers. It is much slower to fit.poisson: for non-negative count targets. It requires every target to be zero or greater.
Use absolute_error when a few extreme targets would otherwise drag leaf means away from typical values. Accept the longer training time.
Fitting a regression tree with scikit-learn
The next example fits noisy sine data. It also shows a property of regression trees that surprises many people: they cannot extrapolate.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.RandomState(0)
X = np.sort(5 * rng.rand(80, 1), axis=0)
y = np.sin(X).ravel() + 0.1 * rng.randn(80)
reg = DecisionTreeRegressor(max_depth=3, min_samples_leaf=5, random_state=0)
reg.fit(X, y)
print(reg.predict([[1.0], [2.5], [4.0]]))
far = reg.predict([[5.0], [10.0], [100.0]])
print(len(set(far))) # 1: all three land in the same rightmost leafThe first print shows three different predictions, one for each region of the input. The second shows that points far beyond the training range all receive the same value. Training inputs run from 0 to just under 5, so the rightmost leaf covers everything above its last threshold, including x = 100.
What the fitted function looks like
A regression tree is a piecewise-constant function. A tree with k leaves has exactly k distinct output values, and each is the mean of one region. Three consequences follow.
- The prediction is a staircase, not a smooth curve. Even a smooth target like a sine wave is approximated by flat steps.
- With few leaves, the steps are coarse and the tree underfits. With many leaves, it follows the noise.
- Outside the training range, the prediction stays flat at the value of the nearest edge leaf. A linear model would continue the trend, but a tree never does.
Fit the tree on prices from 2020 to 2023 and ask for 2026, and you get roughly the 2023 level. If your task needs extrapolation, consider a linear model, or a hybrid that fits a trend first and uses a tree on the residuals.
Controlling complexity
A regression tree left to grow fully will give every training sample its own leaf. Each leaf predicts that sample's exact target, so training error is zero and the model has memorized the noise. The same controls from the earlier chapters apply:
max_depthlimits the number of levels. Depth d allows at most 2^d leaves.min_samples_leafstops splits that would create a leaf with too few samples. In regression this has a second benefit: each leaf mean averages at least that many noisy targets, so it is a steadier estimate.min_samples_splitandmin_impurity_decreasestop splitting nodes that are small or that gain little.ccp_alphaapplies cost-complexity pruning, where the error term is the total squared error of the leaves.
Evaluating a regression tree
Accuracy no longer makes sense, so use regression metrics on held-out data or in cross-validation:
- R² (the default
.score()): 1.0 is perfect and 0.0 matches a model that always predicts the mean of the training targets. It can be negative on test data. - Mean squared error and root mean squared error: in the target's units (RMSE), which is easier to explain to stakeholders.
- Mean absolute error: less dominated by outliers.
The diagnosis for overfitting is the same as before. A large gap between training R² and validation R² means the tree is too deep. Use cross_val_score with scoring="neg_root_mean_squared_error" or "r2" to choose depth and leaf size. Scikit-learn negates error metrics so that larger is always better.
Common errors
- Expecting smooth output. The prediction is a step function. If you need smoothness, ensembles average many steps and look smoother.
- Expecting extrapolation. Predictions outside the training range are flat.
- Using
criterion="poisson"with negative targets. Scikit-learn raises an error. - Reporting training R² as model quality. A fully grown tree scores 1.0 on training data and tells you nothing.
- Scaling features for the tree. Trees compare each feature to a threshold, so monotonic transformations of a feature do not change the splits. Scaling is unnecessary, though it does no harm.
Exercise
A node holds the points x = 1, 2, 3, 4 with targets y = 1, 3, 9, 11. Compute the parent variance, then compare the variance reduction of the thresholds 1.5 and 2.5. Which threshold does a regression tree choose, and what does each child leaf predict?
Show answer
The parent mean is 6, the squared deviations are 25, 9, 9, 25, and the parent variance is 68 / 4 = 17. For threshold 1.5, the left child is [1] with variance 0, and the right child is [3, 9, 11] with mean about 7.67 and variance about 11.56. The weighted variance is (1 · 0 + 3 · 11.56) / 4 ≈ 8.67, so the reduction is about 8.33. For threshold 2.5, the left child is [1, 3] with mean 2 and variance 1, and the right child is [9, 11] with mean 10 and variance 1. The weighted variance is 1, so the reduction is 16. The tree chooses 2.5. The left leaf predicts 2 and the right leaf predicts 10.
Exercise
You fit a regression tree on house prices for homes up to 250 square meters. It predicts the same price for a 400 square meter house as for a 250 square meter one. Why does it do this, and what is one way to handle it?
Show answer
The tree is piecewise constant. Every input above the last split threshold falls into the same rightmost leaf, which predicts the mean of the training prices in that leaf. The tree has no mechanism to continue a trend beyond the data. You can use a model that extrapolates, such as a linear model, or fit a linear trend first and train the tree on its residuals.