Decision trees · Regression

How decision trees learn to predict numbers

A classification tree predicts a label. A regression tree predicts a number. The surprising part is how little of the procedure needs to change.

By the end

You will be able to explain how a regression tree judges a split, what it predicts inside each leaf, and why we need to tell it when to stop growing.

Recap

The procedure we already have

In Chapter 1, we invented a procedure that could repeatedly find useful questions and separate data into meaningful regions. Those regions could then predict a class for a new row we had not seen before.

Creating the tree involved three plain steps:

  1. Propose a split.
  2. Judge the two groups it creates.
  3. Repeat inside the new groups.

This is a powerful idea, but our first tree was deliberately small. Real tree-based algorithms also need to deal with missing data, different kinds of input features, very large datasets, and the danger of growing too much. We will address those problems one at a time in later chapters.

For now, we will change the kind of prediction the tree makes: instead of a class, we want a number.

A new prediction

From classification to regression

In supervised machine learning, two common prediction tasks are classification and regression.

Classification chooses from a set of labels. Predicting whether a seed will struggle or thrive from the water and sunlight it receives is classification: the answer is one of two named classes.

Predicting tomorrow’s average temperature is different. The answer could be 18.2°C, 18.3°C, or another number in between. This is regression.

A compact way to remember the difference is:

In the last lesson, we used Gini impurity to judge a split. Gini is built for classes: it measures how mixed the class labels are inside a group. When our target is a continuous number, there are no classes for Gini to count.

The good news is that we do not need to invent the tree again. We can replace the way we judge a split and keep the same core loop: propose, judge, repeat.

The new score

How can we judge a regression split?

In a small classification example, we can often see a useful separation. Put two features on two axes, draw one class as circles and another as squares, and a clear dividing line may stand out.

For regression, let us use a simple example too. Imagine that we want to predict crop yield from the amount of fertilizer used on one hectare.

This gives us a hill-shaped pattern, although the two sides do not need to be perfectly symmetrical.

RowFertilizer (kg/hectare)Yield (tons/hectare)
A01.5
B202.4
C403.8
D605.1
E805.7
F1005.4
G1204.8
H1404.2
I1603.7

One input feature, fertilizer, and one numeric target, crop yield. The tree may split only between neighboring fertilizer values.

Alice and Bob are trying to build a model from this data. Alice remembers the first article and starts exploring thresholds. Bob takes a shortcut: he uses the average yield as every prediction.

Bob’s prediction is about 4.07 tons per hectare. It is not absurd. It lands near the middle of the observed yields, so it gives us a useful baseline: before adding a split, can Alice do better than one prediction for everyone?

To answer that, Bob measures the distance from every observed yield to 4.07. Some distances are positive and others are negative, so adding them directly would cancel them out. He squares each distance first, then adds the squared distances.

One prediction for all rowsȳ = 4.07Total squared errorΣ(yᵢ − ȳ)² = 15.64

Divide 15.64 by the nine rows and we get a variance of about 1.738. The total and the variance tell the same story here; the total is nine times larger.

Because Bob predicts the mean, this average squared distance is also the variance of the target values. A smaller variance means the values sit more tightly around their mean, so the mean is a better prediction for that group.

Alice notices something interesting. If she places a threshold at 50 kg/ha, halfway between 40 and 60, the rows on each side can use their own mean. The two groups together have a total squared error of 5.515, much less than Bob’s 15.64. This gives her the new judging rule:

The fertilizer dataset divided at 50 kilograms per hectare
RowFertilizerYield
A0 kg/ha1.5 tons/ha
B20 kg/ha2.4 tons/ha
C40 kg/ha3.8 tons/ha
D60 kg/ha5.1 tons/ha
E80 kg/ha5.7 tons/ha
F100 kg/ha5.4 tons/ha
G120 kg/ha4.8 tons/ha
H140 kg/ha4.2 tons/ha
I160 kg/ha3.7 tons/ha
Variance
Before · all rows
1.738
After · split at 50 kg/ha
Rows A–C
0.896
Rows D–I
0.471
Both new groups vary less around their own mean than all nine rows varied around Bob's single mean.

Try every midpoint threshold and keep the one whose two groups leave the least total squared error.

For a candidate split, the calculation is:

split error = Σi∈L(yᵢ − ȳL)² + Σi∈R(yᵢ − ȳR

The first sum measures the errors around the left group’s mean. The second does the same for the right group. We add them because both groups are part of the model. Equivalently, we can multiply each group’s variance by its number of rows and add the two results.

Before running the playground, predict where the lowest point in the split-error chart will appear. The threshold at 50 is already better than no split, but is it the best of all eight choices?

Playground 1 · judge every split

Sweep the fertilizer thresholds

1 of 8 thresholds tested

Current threshold: fertilizer at or below 10 kilograms per hectare. Split error 8.229.

Data and two group predictions
Crop yield by fertilizer amountNine crop observations form a curved pattern. Vertical residual lines connect each observation to the mean prediction for its current group.12345602040608010012014016010ABCDEFGHIFertilizer (kg/hectare)Yield (tons/hectare)
Left · 1 rowmean 1.5 tons/havariance 0
Right · 8 rowsmean 4.39 tons/havariance 1.029
split error1 × 0+8 × 1.029=8.229
Split error across tested thresholds
Split errorlower is better
1030507090110130150current: 8.229
Lowest error so farfertilizer ≤ 10 kg/hasplit error 8.229 · improvement 7.411

If you run the full sweep, the best first threshold is 30 kg/ha. The left group predicts 1.95 tons/ha, the right group predicts about 4.67 tons/ha, and their combined squared error is about 4.119.

This is the same search we used for classification. We still test the midpoints one by one and remember the best result. Only the score has changed: instead of looking for less class mixture, we look for less squared prediction error.

The leaf value

But what is the prediction?

We now know how to choose a regression split, but we still need a prediction for each resulting group.

The fix is small: take the mean inside each leaf.

one learned questionfertilizer ≤ 30 kg/ha?
yes · left leaf
A1.5B2.4

(1.5 + 2.4) ÷ 2

predict 1.95 tons/ha
no · right leaf
C3.8D5.1E5.7F5.4G4.8H4.2I3.7

(3.8 + 5.1 + 5.7 + 5.4 + 4.8 + 4.2 + 3.7) ÷ 7

predict 4.67 tons/ha
A regression leaf stores one prediction: the average target value of the training rows that reach it.

If we stop Alice’s model after the first split, fertilizer amounts at or below 30 kg/ha receive the left mean, 1.95 tons/ha. Larger amounts receive the right mean, about 4.67 tons/ha. These are better estimates for the training data than Bob’s single 4.07 because the split lowered the total squared error.

The mean is not an arbitrary choice. Among all possible single-number predictions for a group, the mean is the one that produces the smallest squared error. Since squared error is the score we chose, the mean and the score belong together.

Tree size

But when should the tree stop?

In our first classification example, we stopped once every leaf was pure: all rows in a leaf had the same class.

Regression has no classes to make pure. With a finite dataset, the tree will not literally grow forever, but it can keep splitting until almost every leaf holds one training row. Then its predictions copy the training data very closely and may work poorly on new data.

We therefore give the tree a stopping rule. Common choices include:

  1. Maximum depth: stop after a fixed number of nested questions.
  2. Minimum rows per leaf: reject splits that create groups that are too small.
  3. Small-enough variance: stop when the target values in a group are already close.
  4. Minimum improvement: split only when the error falls by a meaningful amount.

These rules all make the same tradeoff. A smaller tree gives rougher, steadier predictions. A larger tree follows the training data more closely. In the next playground, change one stopping rule at a time and predict how many leaf predictions the tree will create.

Playground 2 · choose when to stop

Watch the same search grow a regression tree

0 of 5 decisions made

Maximum tree depth. Stop after the tree has asked a fixed number of nested questions.

  1. Propose a splittry every threshold in the group
  2. Judge the two groupskeep the split only if it lowers the error
  3. Repeat inside each grouprecurse until a stopping rule fires
Step 1 of 5Propose & judge — the split for the whole dataset wins.

Across the whole dataset (9 rows, mean 4.07 tons/ha) the search tried every threshold. The best is fertilizer ≤ 30, which cuts the squared error by 11.521. We accept it and split into two smaller groups — then repeat the same search inside each one.

Regions become fixed predictions
Crop yield by fertilizer amountNine crop observations form a curved pattern. Vertical residual lines connect each observation to the mean prediction for its current group.123456020406080100120140160ABCDEFGHIFertilizer (kg/hectare)Yield (tons/hectare)
0160 kg/ha · 9 rowspredict 4.07 tons/ha
Each local winner becomes one question
checking this group9 rowsA B C D E F G H I · variance 1.738

Beyond one column

More features, same two loops

Our fertilizer example used one feature so we could see the new regression score without changing anything else. A real table usually gives the tree more than one possible column to ask about.

Return to the greenhouse, now with twelve plots. For each plot we know the temperature, the water supplied per week, the sunlight per day, and the crop yield we want to predict. The target is still a number. Only the number of possible questions has grown.

The search needs two loops:

  1. For each feature, choose one column.
  2. For each midpoint between distinct values in that column, measure the split error.

The tree remembers the candidate with the lowest error across both loops. Then recursion sends each new group through the same search again.

Temperature has 11 distinct gaps, water has 9, and sunlight has 7, so the root compares 27 candidates in total. Repeated values do not create an extra threshold because they cannot be separated by a midpoint.

Before selecting a feature below, make a prediction: which column can create the lowest-error first split? The points keep the same vertical target axis as you switch features. Only the horizontal feature and its threshold change.

Playground 3 · loop over features

Compare each feature's best split

11 + 9 + 7 = 27 root candidates
Training data · selected feature highlighted
Greenhouse measurements and crop yield for twelve training rows
RowTemperature (°C)Water per week (L)Sunlight per day (h)Yield (tons/ha)
A1636.51.7
B171.531.9
C18452
D201.263.8
E231.63.54
F26274.1
G2132.55
H243.535.1
I2743.55.2
J223.25.55.6
K253.765.8
L284.26.55.9

Search every distinct midpoint in one feature and keep its lowest-error split. The root then keeps the lowest of the three feature winners.

Data and two group predictions
Crop yield predicted from temperatureTwelve greenhouse rows are plotted by temperature and crop yield. A vertical threshold creates two groups, and a horizontal mean predicts each group.2345616182022242628predict 1.7predict 4.416.5ABCDEFGHIJKLTemperature (°C)Yield (tons/hectare)
Split error by threshold
Split error · lower is better16.517.51920.521.522.523.524.525.526.527.5best · 5.129current · 19.76temperature threshold (°C)
Best split for temperaturetemperature19 °Csplit error 5.129

The final decision tree

The winner changes inside each group

stop when improvement < 0.25
questionTemperature19 °C?
yes · ≤
leaf · 3 rowspredict 1.87 tons/haA B C
no · >
questionWater per week2.5 L?
yes · ≤
leaf · 3 rowspredict 3.97 tons/haD E F
no · >
questionSunlight per day4.5 h?
yes · ≤
leaf · 3 rowspredict 5.1 tons/haG H I
no · >
leaf · 3 rowspredict 5.77 tons/haJ K L

At the root, the best temperature question leaves a split error of about 5.129. The best water question leaves 19.542, and the best sunlight question leaves 25.302. Temperature therefore wins the first local search with the threshold 19°C.

The process does not stop using the other columns. Inside the warmer group, water at 2.5 L per week becomes the next local winner. Inside the warm, well-watered group, sunlight at 4.5 hours per day wins the third search. With a minimum improvement of 0.25, the small final tree uses all three features and leaves four mean predictions.

This is the same generalization we made for classification. More columns create more candidates, not a new training algorithm. Classification keeps the split with the largest drop in class mixture. Regression keeps the split with the lowest remaining squared error. The two loops and the recursion stay in place.

The entire regression-tree procedure now fits in one compact picture:

  1. For each feature, propose midpoints between its distinct values.
  2. Judge each threshold by the squared error left around the two group means.
  3. Keep the lowest-error split across every feature and threshold.
  4. Repeat inside the new groups until a stopping rule says that a group is a leaf.
  5. Predict the mean of the training targets inside that leaf.

Keep the smallest useful mental model

A regression tree is the same search, judged by squared error.

At each node, try every candidate split. Keep the one that leaves the least squared error around the two group means. Then repeat inside the groups that are still spread out, and let each leaf predict its mean.

We did not replace the tree algorithm. We changed the question used to judge a split and the value stored in a leaf — and that was the whole point. Squaring the distance to a group’s mean turned “these numbers are close together” into a quantity the same loop could minimize, exactly as Gini gain once did for class mixture. The propose–judge–repeat structure did the rest.

You understand the mechanism if you can now…

  • explain why the mean is the leaf prediction that squared error rewards;
  • score a candidate threshold from the squared error of its two groups;
  • state the regression training algorithm as two loops plus recursion;
  • name a stopping rule and predict how it changes the tree’s size;
  • explain how the same threshold search compares several features;
  • say what changed from the classification tree — and what did not.