Asiman Data School

Module 3, topic 31, week 16, Tuesday

Random Forests and ensemble learning (bagging) - Regression

The forest of Topic 30 for a number: regression trees that split by the squared error and predict means, a forest that takes the mean of its trees and cannot go beyond its training values, R², MAE and RMSE, the out-of-bag R², and bagging around trees and linear regression, on 10,000 raw car adverts from the first line of preprocessing to the scores of every model.

Introduction: from a class to a number

The eleventh lesson of Module 3. Topic 30 built random forests and bagging for a class: will a customer leave the bank or not? This lesson uses the same two methods for a number: the price of a car. Most of the ideas are exactly the same, and Topic 30 explains them in full; this lesson repeats them in one or two sentences and points to the place in Topic 30. The time goes to what is new when the target is a number:

  • how a regression tree chooses its questions (the squared error instead of the Gini impurity), and what its leaves predict;
  • how a regression forest makes its prediction (the mean of the trees), and what it cannot do (predict a price higher than every training price);
  • the measures of regression from Topic 22: R², MAE and RMSE;
  • the default max_features of RandomForestRegressor, which makes the default forest plain bagging of trees;
  • a new data file with real problems: repeated rows, impossible values, missing values and a column with hundreds of categories.

The lesson has three steps, as Topic 30. On paper: what changes from classification to regression, how a regression tree chooses its splits (worked by hand), how the forest predicts, the hyperparameters and the measures. Then the project on car_prices.csv: data import, preprocessing, the random forest, its tuning and its measures. Then bagging: the same project continues with bagging around a decision tree and around linear regression, and the scores of all models are compared.

You need: random forests and bagging (Topic 30), decision trees (Topic 29), linear regression and the measures R², MAE and RMSE (Topic 22), the train/test split and cross-validation (Topic 23), encoding (Topic 25), and the cleaning of Topic 11 (missing values and repeated rows).

What you will learn

  1. 1.What stays the same and what changes when a forest predicts a number
  2. 2.How a regression tree chooses its questions with the squared error, and why its leaves predict a mean
  3. 3.How a regression forest predicts: the mean of the predictions of its trees
  4. 4.Why a forest cannot predict outside the range of the training prices
  5. 5.The hyperparameters of RandomForestRegressor, and why its default max_features matters
  6. 6.The measures R², MAE and RMSE, and the out-of-bag R²
  7. 7.What repeated rows, impossible values, missing values and many categories mean for the model
  8. 8.Bagging around any regression model with BaggingRegressor: around trees and around linear regression
  9. 9.A whole project: from the file to a tuned forest, bagged models, and the scores of all of them
The words of this lesson
WordMeaning
Regression foresta random forest whose target is a number; it predicts the mean of its trees
Regression treea decision tree whose leaves predict a number: the mean of the training rows in the leaf
Squared error of a nodethe mean of the squared distances of the prices in a node from their mean (the variance of the node)
R²the share of the variance of the target that the model explains; 1 is perfect, 0 is as good as always predicting the mean
MAEmean absolute error: the typical error, in the unit of the target (manats)
RMSEroot mean squared error: also in manats, but large errors count more
OOB R²the R² of the forest on its out-of-bag rows: a free validation score
Extrapolationpredicting outside the range of the training data; a forest cannot do it
BaggingRegressorbagging around any regression model

1From a class to a number

1.1What stays the same

Everything that makes a random forest a random forest is the same as in Topic 30:

What stays the same
IdeaIn shortWhere in Topic 30
Bootstrap sampleevery tree gets as many rows as the training data, drawn with replacementPart 2, Step 1
Out-of-bag rowsabout 37 percent of the rows are not in a tree's samplePart 2, Step 1
Random featuresat every split a tree chooses among a few random features (max_features)Part 2, Step 2
Deep treesthe trees are grown without limits by default; the averaging takes care of their variancePart 2, Step 2
Why many trees helpdifferent trees make different mistakes, and the mistakes cancel in the averagePart 2
Variance of an averageρ σ2+(1−ρ) σ2n\rho \, \sigma^2 + \frac{(1 - \rho)\,\sigma^2}{n}: more trees shrink the second part, less correlated trees the firstPart 2
More trees never overfitthey only make the average more stable, and cost timePart 4
Baggingthe same model on many bootstrap samples, the answers combined; it works around any modelPart 9
Bagging cures varianceit helps unstable models (deep trees) and hardly changes stable onesPart 9
Extremely randomized treesrandom thresholds as well as random featuresPart 9

If one of these is not clear, read its place in Topic 30 first: this lesson uses all of them.

1.2What changes

What changes
Classification (Topic 30)Regression (this topic)
Targeta class: leaves (1) or stays (0)a number: the price of a car in manats (AZN)
A tree chooses its split bythe Gini impurity or the entropythe squared error
A leaf predictsthe share of each class in the leafthe mean of the target in the leaf
The forest predictsthe mean of the trees' probabilitiesthe mean of the trees' predictions
Measuresaccuracy, precision, recall, F1, AUC (Topic 28)R², MAE, RMSE (Topic 22)
Default max_features"sqrt": the square root of the number of features1.0: all features
oob_score_ holdsthe out-of-bag accuracythe out-of-bag R²
class_weightfor unbalanced classesdoes not exist: there are no classes
In scikit-learnRandomForestClassifier, BaggingClassifierRandomForestRegressor, BaggingRegressor

1.3Where regression forests are used

  • Prices: cars (the project of this lesson), flats and houses, insurance premiums.
  • Demand: how many products a shop will sell next week, how many taxis a city needs at 8 a.m.
  • Energy: the electricity a building will use tomorrow, the power of a wind farm.
  • Medicine: how many days a patient will stay in hospital.
  • Science: the yield of a field from soil and weather measurements.
  • As a strong first model: as for classes, a random forest with its default settings is a good first try for any table of data with a numerical target.

Try it yourself

(a) What does a leaf of a regression tree predict? (b) How does RandomForestRegressor combine its trees? (c) What is the default max_features of RandomForestRegressor? (d) What does oob_score_ hold for a regression forest?

Show a hint
Look at the table "What changes".
Show the solution

Answer: (a) the mean of the leaf; (b) the mean of the trees' predictions; (c) 1.0, all features; (d) the out-of-bag R².

Everything that makes a forest a forest is the same as in Topic 30; what changes is the target, so the leaves, the combination of the trees and the measures work with numbers.

2How a regression tree chooses its questions

2.1The squared error of a node

A regression tree asks the same kind of questions as the trees of Topic 29 ("year ≤ 2015.5?"), but it needs a different measure of a good split. There are no classes to be pure. Instead, a good group is a group of cars whose prices are close to each other.

The tree measures this with the squared error of a node: the mean of the squared distances of the prices from their mean.

squared error of a node=mean of (price−mean price)2\begin{aligned} & \text{squared error of a node} \\[4pt] &= \text{mean of } (\text{price} - \text{mean price})^2 \end{aligned}

This is the variance of the prices in the node (Topic 18). A node with similar prices has a small squared error; a node that mixes cheap and expensive cars has a large one.

A leaf predicts the mean of the prices of its training cars. The mean is the one number with the smallest squared error to a group of numbers, so the leaf's prediction and the tree's measure fit together.

Like a classification tree, the tree tries every feature and every threshold, and takes the split with the lowest weighted squared error of the two groups:

error after the split=nleftn×errorleft+nrightn×errorright\begin{aligned} & \text{error after the split} \\[4pt] &= \frac{n_{\text{left}}}{n} \times \text{error}_{\text{left}} \\[4pt] &\quad + \frac{n_{\text{right}}}{n} \times \text{error}_{\text{right}} \end{aligned}

2.2An example with six cars

Six cars, their years and their prices in thousands of manats:

An example with six cars
CarABCDEF
Year200820112014201720192022
Price (thousand AZN)81012242832

Before any split, the node holds all six cars:

mean=8+10+12+24+28+326=1146=19squared error=112+92+72+52+92+1326=5266=87.667\begin{aligned} \text{mean} &= \frac{8 + 10 + 12 + 24 + 28 + 32}{6} \\[4pt] &= \frac{114}{6} = 19 \\[8pt] \text{squared error} &= \frac{11^2 + 9^2 + 7^2 + 5^2 + 9^2 + 13^2}{6} \\[4pt] &= \frac{526}{6} = 87.667 \end{aligned}

The candidate thresholds lie halfway between neighbouring years, as in Topic 29: 2009.5, 2012.5, 2015.5, 2018 and 2020.5. The threshold 2015.5 puts A, B, C on the left and D, E, F on the right:

left mean=8+10+123=10left error=22+02+223=83=2.667right mean=24+28+323=28right error=42+02+423=323=10.667\begin{aligned} \text{left mean} &= \frac{8 + 10 + 12}{3} = 10 \\[6pt] \text{left error} &= \frac{2^2 + 0^2 + 2^2}{3} = \frac{8}{3} = 2.667 \\[10pt] \text{right mean} &= \frac{24 + 28 + 32}{3} = 28 \\[6pt] \text{right error} &= \frac{4^2 + 0^2 + 4^2}{3} = \frac{32}{3} = 10.667 \end{aligned}
error after the split=36×2.667+36×10.667=1.333+5.333=6.667\begin{aligned} & \text{error after the split} \\[4pt] &= \tfrac{3}{6} \times 2.667 + \tfrac{3}{6} \times 10.667 \\[4pt] &= 1.333 + 5.333 = 6.667 \end{aligned}

The threshold 2012.5 puts only A and B on the left:

left mean=8+102=9left error=12+122=1right mean=12+24+28+324=24right error=122+02+42+824=2244=56\begin{aligned} \text{left mean} &= \frac{8 + 10}{2} = 9 \\[6pt] \text{left error} &= \frac{1^2 + 1^2}{2} = 1 \\[10pt] \text{right mean} &= \frac{12 + 24 + 28 + 32}{4} = 24 \\[6pt] \text{right error} &= \frac{12^2 + 0^2 + 4^2 + 8^2}{4} \\[4pt] &= \frac{224}{4} = 56 \end{aligned}
error after the split=26×1+46×56=0.333+37.333=37.667\begin{aligned} & \text{error after the split} \\[4pt] &= \tfrac{2}{6} \times 1 + \tfrac{4}{6} \times 56 \\[4pt] &= 0.333 + 37.333 = 37.667 \end{aligned}

All five thresholds:

An example with six cars
ThresholdLeftRightError after the split
year ≤ 2009.5AB, C, D, E, F63.467
year ≤ 2012.5A, BC, D, E, F37.667
year ≤ 2015.5A, B, CD, E, F6.667
year ≤ 2018A, B, C, DE, F27.167
year ≤ 2020.5A, B, C, D, EF53.867

The tree chooses year ≤ 2015.5: it lowers the squared error from 87.667 to 6.667. Its two leaves predict the means: 10 thousand manats for an older car, 28 thousand for a newer one. (DecisionTreeRegressor(max_depth=1) finds exactly this split and these two values.)

01020302008201220162020ABCDEFyear ≤ 2015.5?
  • a car
  • a leaf: the mean of its cars
  • the threshold
The best split of the six cars. The dashed line is the question "year ≤ 2015.5?". Each leaf predicts the mean price of its cars: 10 thousand manats for A, B and C, 28 thousand for D, E and F. The prices of each group lie close to their mean, so the squared error after the split is small (6.667).

Choose the threshold of the question "year ≤ ...?" for the six cars, and compare the squared error after the split.

01020302008201220162020ABCDEFyear ≤ 2012.5?

Left: A, B, mean 9, error 1. Right: C, D, E, F, mean 24, error 56.

Error after the split: 37.667 (before: 87.667). Another threshold gives a lower error.

Each leaf predicts the mean of its cars. A good question puts cars with similar prices together.

2.3The other criteria

DecisionTreeRegressor and RandomForestRegressor take the measure as criterion:

The other criteria
criterionThe node's errorThe leaf predicts
"squared_error" (default)the mean squared distance from the meanthe mean
"absolute_error"the mean absolute distance from the medianthe median; less moved by a few very expensive cars, but much slower
"friedman_mse"the squared error with a correction used by boosting (Topics 37 to 40)the mean
"poisson"a measure for counts (numbers of sales, of visits)the mean

The default is the right choice almost always, and this lesson keeps it.

2.4A full tree learns every price by heart

A tree without limits keeps splitting until each leaf holds a single car, or cars with exactly the same features. Then a leaf "predicts" the price of one training car: the tree reproduces the training prices almost perfectly and has a training R² close to 1. On new cars it does much worse: one full tree overfits, exactly as in Topic 29. The project shows it with numbers (Part 9).

Try it yourself

Five cars were made in 2010, 2012, 2014, 2019 and 2021 and cost 6, 8, 10, 20 and 26 thousand AZN. (a) What is the squared error of the node with all five cars? (b) What is the error after the split "year ≤ 2016.5"? (c) What does its right leaf predict?

Show a hint
The mean of all five is 14. After the split: the left group 6, 8, 10 and the right group 20, 26, each around its own mean, weighted by its share of the cars.
Show the solution

Answer: (a) 59.2; (b) 5.2; (c) 23 thousand AZN.

node=82+62+42+62+1225=2965=59.2left error=22+02+223=2.667right error=32+322=9after=35×2.667+25×9=1.6+3.6=5.2\begin{aligned} \text{node} &= \frac{8^2 + 6^2 + 4^2 + 6^2 + 12^2}{5} \\[4pt] &= \frac{296}{5} = 59.2 \\[8pt] \text{left error} &= \frac{2^2 + 0^2 + 2^2}{3} = 2.667 \\[6pt] \text{right error} &= \frac{3^2 + 3^2}{2} = 9 \\[8pt] \text{after} &= \tfrac{3}{5} \times 2.667 + \tfrac{2}{5} \times 9 \\[4pt] &= 1.6 + 3.6 = 5.2 \end{aligned}

The split lowers the error from 59.2 to 5.2. The left leaf predicts the mean 8, the right leaf the mean 20+262=23\frac{20 + 26}{2} = 23.

3How a regression forest predicts

3.1Three steps

The forest is built exactly as in Topic 30; only the last step differs.

training data7,407 carssample 1sample 2sample 100tree 118,500 AZNtree 221,000 AZNtree 10022,600 AZNthe forestmean of the predictions
The three steps of a regression forest. Step 1: every tree gets its own bootstrap sample of the training cars. Step 2: a tree is grown on each sample with the squared error, and for a new car each tree predicts a price. Step 3: the forest predicts the mean of these prices.
  1. Every tree gets its own bootstrap sample of the training cars.
  2. Every tree is grown with the squared error, choosing at each split among max_features features.
  3. For a new car, every tree gives a price, and the forest predicts their mean.

Three trees and one car:

Three steps
TreeIts prediction
Tree 118,500 AZN
Tree 221,000 AZN
Tree 322,600 AZN
prediction of the forest=18,500+21,000+22,6003=62,1003=20,700 AZN\begin{aligned} & \text{prediction of the forest} \\[4pt] &= \frac{18{,}500 + 21{,}000 + 22{,}600}{3} \\[4pt] &= \frac{62{,}100}{3} = 20{,}700 \text{ AZN} \end{aligned}

There is no vote and no threshold of 0.5: the mean of the numbers is the answer. A forest of 100 trees takes the mean of 100 prices.

3.2Why the mean of many trees is better

Each full tree predicts the price of one or a few training cars that look like the new car: a rough guess with a large variance. Another bootstrap sample would give another guess. The mean of 100 such guesses varies much less. The formula of Topic 30 (Part 2) says how much less:

variance of the average=ρ σ2+(1−ρ) σ2n\begin{aligned} & \text{variance of the average} \\[4pt] &= \rho \, \sigma^2 + \frac{(1 - \rho) \, \sigma^2}{n} \end{aligned}

With 100 trees the second part is tiny; the first part, the correlation ρ\rho of the trees, is what is left, and only more different trees make it smaller. Part 8 measures ρ\rho on the cars.

00.30.6111020304050
  • ρ = 0
  • ρ = 0.3
  • ρ = 0.6
The variance of the average of n trees, each with the variance 1, for three correlations ρ. Without correlation the variance falls towards 0. With ρ = 0.3 it can never fall below 0.3, however many trees there are: only less correlated trees lower that floor.

3.3What a forest cannot do: predict outside the training prices

Every leaf predicts a mean of training prices. A mean of prices is never higher than the highest of them and never lower than the lowest. So:

  • No tree can predict a price higher than the most expensive training car, or lower than the cheapest.
  • The forest's prediction is a mean of such predictions, so the forest cannot either.

A forest that has seen cars up to 160,000 AZN will never predict 200,000 AZN, even for a brand-new luxury car. And a car newer than all training cars gets about the price of the newest training cars. Linear regression is different: its line goes on, for better or worse.

025507510019952005201520252035no training carsafter this year
  • one tree (max_depth=3)
  • forest of 100 such trees
  • linear regression
Three models that know only the year of 300 cars of the file. One tree of depth 3 predicts with a few steps; the forest of 100 such trees is a finer staircase. After 2024, the newest year in the data, both stay flat: every leaf is a mean of training prices. The line of linear regression keeps rising.

The picture uses only the year of 300 cars of the file. One tree predicts with a few steps; the forest of 100 such trees is a finer staircase, because every tree puts its steps in slightly different places. After the newest training year both are flat. The line of linear regression continues to rise.

For car prices this is rarely a problem: new cars are rarely far outside the data. For targets that grow over time (sales that grow every year, prices with inflation) it matters, and a model that can extrapolate, or a target without the trend, is needed.

Try it yourself

(a) Four trees predict 12,000, 15,000, 13,500 and 14,300 AZN for a car. What does the forest predict? (b) The training prices lie between 3,000 and 80,000 AZN. Can the forest ever predict 95,000 AZN? (c) Which of the two models can predict above the highest training price?

Show a hint
The forest takes the mean. Every leaf is a mean of training prices.
Show the solution

Answer: (a) 13,700 AZN; (b) no; (c) linear regression.

12,000+15,000+13,500+14,3004=54,8004=13,700\begin{aligned} & \frac{12{,}000 + 15{,}000 + 13{,}500 + 14{,}300}{4} \\[4pt] &= \frac{54{,}800}{4} = 13{,}700 \end{aligned}

A mean of prices between 3,000 and 80,000 stays between them, and so does a mean of such means. The line of linear regression goes on.

4The hyperparameters of RandomForestRegressor

RandomForestRegressor has the hyperparameters of RandomForestClassifier (Topic 30, Part 4), with these differences:

The hyperparameters of RandomForestRegressor
HyperparameterDefaultRole in a regression forest
n_estimators100the number of trees. More trees: a more stable mean, never more overfitting, but slower.
criterion"squared_error"the measure of every tree (Part 2)
max_features1.0the share of the features each split may choose from. The default 1.0 means all features: then the forest is plain bagging of trees. 0.33 (a third), 0.5, "sqrt" or a number make it a real random forest.
max_depthNonethe depth of every tree; the default grows full trees
min_samples_split2the smallest node that may still be split
min_samples_leaf1the smallest leaf: its prediction is the mean of at least this many cars
bootstrapTrueevery tree gets a bootstrap sample
max_samplesNonethe size of each bootstrap sample; None: as many rows as the training data
oob_scoreFalsewith True the forest computes its R² on the out-of-bag rows: oob_score_
n_jobsNonehow many processor cores train the trees at the same time; -1 uses all of them
random_stateNonethe seed for all random choices

There is no class_weight: a number has no classes to weight.

4.1The default max_features of a regression forest

For classes, scikit-learn's default is "sqrt", the random forest of Topic 30. For a number the default is 1.0, every feature at every split. So RandomForestRegressor() with its default settings is bagging of full trees: only the bootstrap samples make its trees differ. The project shows that it gives practically the same scores as BaggingRegressor around a tree (Part 9).

Why this default? On many regression data sets bagged trees are already good, and the random features add less than for classes. But they often still help. Leo Breiman, who invented random forests, suggested a third of the features for regression. Treat max_features as the first hyperparameter to tune: try 1.0, 0.5, 0.33 and "sqrt", and compare them with the out-of-bag R² or with cross-validation.

4.2Is a regression forest safe from overfitting?

Topic 30 (Part 4) answered this for classes, and the answer is the same for numbers:

  • More trees never make it overfit. They only make the mean steadier (Part 8 shows the curve).
  • Its full trees do learn the training prices by heart. The project's forest has an R² of 0.98 on the training cars and 0.865 on the test cars. The gap is real overfitting of the single trees, made harmless by the averaging; it means that a forest must never be judged on its training data.
  • The settings of the trees can still help or hurt: max_features, min_samples_leaf and max_depth are tuned with the out-of-bag R² or with cross-validation.

So a regression forest is robust, not immune: hard to spoil with its main setting, good with the defaults, and judged on data it has not seen.

4.3Which ones matter most

  • max_features: as above, the first one to try.
  • n_estimators: more is better until the scores flatten; limited by time only.
  • min_samples_leaf and max_depth: they make every tree simpler. In Topic 30 larger leaves made the probabilities smoother and raised the AUC. For prices, a leaf of one car is often best: every limit makes the predicted prices coarser. The project checks it.

They are chosen with the out-of-bag R² or with cross-validation on the training data (Topic 23), never with the test data. Searching several hyperparameters at once is the subject of Topic 42.

Which hyperparameter is it?

1 of 8

Its default for a regression forest, 1.0, makes the forest plain bagging of trees.

Try it yourself

A data set has 40 features. (a) How many features does each split of a default RandomForestRegressor try? (b) And with max_features=0.25? (c) Does raising n_estimators from 100 to 500 make the forest overfit? (d) Which setting gives the out-of-bag R²?

Show a hint
The default share is 1.0; a share is multiplied by the number of features.
Show the solution

Answer: (a) 40; (b) 10; (c) no; (d) oob_score=True.

1.0×40=40,0.25×40=101.0 \times 40 = 40, \qquad 0.25 \times 40 = 10

More trees only steady the mean. The out-of-bag R² comes with oob_score=True.

5Measures and preprocessing

5.1The measures of regression

A regression model is judged by how far its predictions are from the true values. Topic 22 introduced the three common measures. With nn cars, true prices yy, predicted prices y^\hat{y} and the mean price yˉ\bar{y}:

MAE=1n∑∣y−y^∣\text{MAE} = \frac{1}{n} \sum |y - \hat{y}|
RMSE=1n∑(y−y^)2\text{RMSE} = \sqrt{\frac{1}{n} \sum (y - \hat{y})^2}
R2=1−∑(y−y^)2∑(y−yˉ)2R^2 = 1 - \frac{\sum (y - \hat{y})^2}{\sum (y - \bar{y})^2}

Four cars, prices in thousands of manats:

The measures of regression
CarTrue price yyPredicted y^\hat{y}Error y−y^y - \hat{y}
12022−2-2
215141
330273
425250
MAE=2+1+3+04=64=1.5MSE=4+1+9+04=144=3.5RMSE=3.5=1.871\begin{aligned} \text{MAE} &= \frac{2 + 1 + 3 + 0}{4} = \frac{6}{4} = 1.5 \\[6pt] \text{MSE} &= \frac{4 + 1 + 9 + 0}{4} = \frac{14}{4} = 3.5 \\[6pt] \text{RMSE} &= \sqrt{3.5} = 1.871 \end{aligned}
yˉ=20+15+30+254=904=22.5∑(y−yˉ)2=2.52+7.52+7.52+2.52=6.25+56.25+56.25+6.25=125R2=1−14125=1−0.112=0.888\begin{aligned} \bar{y} &= \frac{20 + 15 + 30 + 25}{4} = \frac{90}{4} = 22.5 \\[8pt] \textstyle\sum (y - \bar{y})^2 &= 2.5^2 + 7.5^2 + 7.5^2 + 2.5^2 \\[4pt] &= 6.25 + 56.25 + 56.25 + 6.25 \\[4pt] &= 125 \\[8pt] R^2 &= 1 - \frac{14}{125} = 1 - 0.112 = 0.888 \end{aligned}
The measures of regression
MeasureUnitWhat it saysWhen to look at it
MAEmanatsthe typical error of a predictionto tell a buyer how far off the price usually is
RMSEmanatslike the MAE, but large errors count much more; always at least the MAEwhen a few large mistakes are costly
R²nonethe share of the variance of the prices that the model explainsto compare models on the same data; 1 is perfect

When the RMSE is much larger than the MAE, a few cars have very large errors. For car prices this is typical: an error of 10 percent on a car of 150,000 AZN is 15,000 AZN.

The four cars of the example (prices in thousands of AZN). Move p, the prediction for car 3, whose true price is 30.

True prices 20, 15, 30, 25; predicted 22, 14, 27, 25; errors −2, 1, 3, 0.

MAE 1.500, RMSE 1.871, R² 0.888.

Move p far from 30: one large error makes the RMSE grow much faster than the MAE, and the R² can even fall below 0 (worse than predicting the mean, 22.5, for every car).

5.2Preprocessing for a regression forest, and for the models still to come

Topic 29 (Part 5) and Topic 30 (Part 5) explained why trees and forests need less preprocessing. For regression it is the same, with two points that matter more now:

  • Scaling: not needed. Every tree only compares a value with a threshold.
  • Encoding: still needed. scikit-learn's forests accept only numbers.
  • Outliers in the features: no harm, for the same reason.
  • Outliers in the target: these do matter. The squared error and the means of the leaves are pulled by very high prices. Check whether they are real (a luxury car) or mistakes (a price typed with an extra zero). Real ones stay.
  • Impossible values: a year 0 or a mileage of three million kilometres is a mistake in the data, not an outlier. Such rows are removed or the values are set to missing.
  • Missing values: recent versions of scikit-learn let trees and forests work with them; in this course they are filled on purpose (Topic 11), with values computed from the training data only (Topic 23).
  • Repeated rows: the same row in the training and in the test data lets a forest of deep trees "remember" its price. They are dropped before the split (Part 6 shows why).
  • A column with hundreds of categories (here the car model, 816 values): one-hot encoding would add hundreds of columns of mostly zeros. It is dropped, or its rare values are grouped.

Bagging puts its own rule on top: the model inside decides its preprocessing. Plain linear regression needs encoded and filled data. It does not need scaling: Topic 24 showed that LinearRegression gives the same predictions with scaled and unscaled features (Ridge and Lasso, Topic 26, do need it).

Preprocessing for a regression forest, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values
Linear regression (22)not needed for the predictionsneededsensitivefill
Ridge, Lasso, logistic regression (26, 27)neededneededsensitivefill
Decision tree (29)not neededneededrobustfill (recent scikit-learn can handle them)
Random forest, bagged trees (30, 31)not neededneededrobustfill (recent scikit-learn can handle them)
Bagging around another model (30, 31)as the model insideas the model insideas the model insideas the model inside
k-nearest neighbours (32, 33)essential: distancesneededsensitivefill
Support vector machines, voting (35, 36)needed for the support vector machine; voting as the models insideneededsensitivefill
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost, LightGBM and CatBoost handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivefill

Try it yourself

Three cars cost 10, 16 and 22 thousand AZN; a model predicts 12, 15 and 22. (a) What is the MAE? (b) What is the RMSE? Give 3 decimals. (c) What is the R²? Give 3 decimals. (d) Does a random forest need scaled features?

Show a hint
The errors are −2-2, 11 and 00; the mean of the true prices is 16.
Show the solution

Answer: (a) 1; (b) 1.291; (c) 0.931; (d) no.

MAE=2+1+03=1RMSE=4+1+03=1.667=1.291R2=1−536+0+36=1−572=0.931\begin{aligned} \text{MAE} &= \frac{2 + 1 + 0}{3} = 1 \\[6pt] \text{RMSE} &= \sqrt{\frac{4 + 1 + 0}{3}} = \sqrt{1.667} = 1.291 \\[6pt] R^2 &= 1 - \frac{5}{36 + 0 + 36} = 1 - \frac{5}{72} = 0.931 \end{aligned}

The trees of a forest only compare values with thresholds, so scaling changes nothing for them.

6The project: from the file to the data for the forest

Now the data: car_prices.csv, 10,000 adverts of cars for sale in Azerbaijan, taken at random from a larger file of adverts. Each row is one advert: the brand and model, the year, the engine, the mileage, the gearbox, the body, the colour, and more. The column price_azn is the price in manats: the target.

The data file: car_prices.csv

10,000 car adverts, 19 columns, not cleaned: repeated adverts, missing values and impossible values are still in it. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

Every step is done again and explained as if it were new, so that the whole workflow is in one place. The cells continue from each other like the cells of a notebook.

The file is not cleaned. It was cut from a much larger file of adverts in only three ways: 10,000 adverts were drawn at random (so that the Python of a browser can work with them), the Azerbaijani words of the adverts were translated into English, and everything about the sellers (names, phone numbers, descriptions, links) was left out. Nothing else was done: the repeated adverts, the missing values, the impossible values, the outliers and the text columns are all still in the file, exactly as the adverts had them. Every preprocessing step happens in this lesson, from the first line of code.

6.1Step 1: read and look

Python
import pandas as pd

df = pd.read_csv("car_prices.csv")

print(df.shape)
print(df.head())

Output

(10000, 19)
        brand    model  year  engine_l  ...  painted   market     city price_azn
0    Mercedes  C 220 d  2002       2.2  ...        0      NaN  Sumgait     11800
1     Changan    Uni-Z  2024       1.5  ...        0      NaN  Sumgait     41400
2  Volkswagen   Passat  2014       1.8  ...        0  America    other     14900
3      Toyota    Prius  2008       1.5  ...        0    Japan     Baku     13700
4         BMW      528  1999       2.8  ...        0      NaN     Baku      8500

[5 rows x 19 columns]

10,000 rows and 19 columns. The features:

Step 1: read and look
ColumnMeaning
brand, modelthe make and the model of the car
yearthe year it was made
engine_l, horsepowerthe engine volume in litres and the power in horsepower
fuel, gearbox, drive, body, colourthe kind of fuel, the gearbox, the driven wheels, the body type, the colour
mileage_kmthe kilometres driven
seats, ownersthe number of seats and of previous owners
is_new, damaged, painted1 for a new car, for a car with accident damage, for a car with repainted parts
marketthe market the car was first sold in (official dealer, Europe, America, Korea, ...)
citywhere the car is sold
price_aznthe price in manats (AZN): the target

6.2Step 2: check

Python, continues from the cells above
print(df.isna().sum())
print(df.duplicated().sum())

Output

brand            0
model            0
year             0
engine_l         0
horsepower    3457
fuel             0
mileage_km       0
gearbox          0
drive            0
body             0
colour           0
seats         2553
owners        3138
is_new           0
damaged          0
painted          0
market        3092
city             0
price_azn        0
dtype: int64
691

Four columns have missing values: horsepower, seats, owners and market. And 691 rows are exact copies of another row: the same car, advertised twice.

6.3Step 3: drop the repeated rows

Python, continues from the cells above
df = df.drop_duplicates()

print(df.shape)

Output

(9309, 19)

Change it and run: remove the line df = df.drop_duplicates() and run the cell check again in your head: the 691 copies would stay in the data.

drop_duplicates() keeps the first of each group of equal rows (Topic 11). This step matters more than it looks. If an advert is in the data twice, the split may put one copy into the training data and the other into the test data. A forest of deep trees has learned the training copy's price exactly, so it "predicts" the test copy perfectly, and the test score looks better than it is. On this file, the same steps without drop_duplicates() give a test R² of 0.907 instead of 0.865: the difference is a lie told by the repeated adverts.

6.4Step 4: impossible values

Python, continues from the cells above
print(df[["year", "engine_l", "mileage_km", "price_azn"]].describe().round(1))

Output

         year  engine_l  mileage_km  price_azn
count  9309.0    9309.0      9309.0     9309.0
mean   2004.2       2.1    194537.2    23501.2
std     119.8       1.1    141071.1    14215.7
min       0.0       0.0         0.0      700.0
25%    2007.0       1.6    103000.0    13500.0
50%    2013.0       2.0    181800.0    21700.0
75%    2016.0       2.2    258571.0    29900.0
max    2024.0      15.0   3259850.0   160000.0

describe() shows the smallest and the largest value of each column. Two things are impossible: a car made in the year 0, and a mileage of more than three million kilometres (a car that drove 200 kilometres every day for 40 years would reach 2.9 million). These are mistakes in the adverts. An engine of 0 litres is not a mistake:

Python, continues from the cells above
print(df.loc[df["engine_l"] == 0, "fuel"].value_counts())

Output

fuel
electric    44
other       10
Name: count, dtype: int64

Electric cars have no engine volume, so 0 is right for them.

6.5Step 5: remove the impossible rows

Python, continues from the cells above
df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]

print(df.shape)

Output

(9259, 19)

Change it and run: change 1950 to 1990 and run: old cars are removed too, which is a decision about the data, not a repair.

The rows with a year before 1950 or more than a million kilometres are removed. (1_000_000 is the number one million; Python allows _ between digits to make it readable.) Removing them is better than keeping them: a forest would learn that "year 0" is a group of cars of its own.

6.6Step 6: drop the column with too many categories

Python, continues from the cells above
print(df["model"].nunique())

df = df.drop(columns=["model"])

Output

797

816 different models. One-hot encoding would add 815 columns, most of them with a single car or a few. The brand, the year, the engine and the body already say much of what the model says, so the column is dropped. (Topic 25 showed other ways for such columns; dropping is the simple one.)

6.7Step 7: the target

Python, continues from the cells above
print(df["price_azn"].describe().round(0))

Output

count      9259.0
mean      23399.0
std       14083.0
min        1200.0
25%       13500.0
50%       21600.0
75%       29900.0
max      160000.0
Name: price_azn, dtype: float64

The prices go from 1,200 to 160,000 AZN; half of the cars cost less than 21,600 AZN (the median), and the mean, 23,399 AZN, is higher: a few expensive cars pull it up.

Python, continues from the cells above
import matplotlib.pyplot as plt

df["price_azn"].plot(kind="hist", bins=50)
plt.xlabel("price (AZN)")
plt.title("Most cars are cheap, a few are very expensive")
plt.show()
Chart: Most cars are cheap, a few are very expensive
Python, continues from the cells above
q1 = df["price_azn"].quantile(0.25)
q3 = df["price_azn"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)

print(upper)
print((df["price_azn"] > upper).sum())

Output

54500.0
256

The IQR rule (Topic 25) finds 256 cars above its upper limit of 54,500 AZN. They are real expensive cars, not mistakes, and a model for this market must price them too: they stay. They are why the RMSE of the models will be much larger than their MAE.

The features have outliers too:

Python, continues from the cells above
for column in ["mileage_km", "engine_l", "horsepower"]:
    q1 = df[column].quantile(0.25)
    q3 = df[column].quantile(0.75)
    upper = q3 + 1.5 * (q3 - q1)
    print(column, upper, (df[column] > upper).sum())

Output

mileage_km 489516.25 238
engine_l 3.1000000000000005 710
horsepower 287.5 218

Hundreds of cars with a long mileage, a large engine or a strong motor. After the impossible rows of Step 5 they are real cars (SUVs, trucks, sports cars, old taxis), and a forest is not disturbed by them: its trees only ask whether a value is above a threshold, so a very large value simply falls on the "above" side (Part 5). They stay. For linear regression, which is sensitive to outliers in the features (Part 5), they would be worth a second look; Part 9 uses it only for a comparison.

6.8Step 8: group the rare brands

Python, continues from the cells above
counts = df["brand"].value_counts()
rare = counts[counts < 50].index

df.loc[df["brand"].isin(rare), "brand"] = "other"

print(df["brand"].nunique())

Output

19

Change it and run: change 50 to 100 and run: fewer brand values are left.

Many brands have only a few cars. counts[counts < 50].index lists the brands with fewer than 50 cars, and they all become "other". 19 brand values are left: enough to tell a Mercedes from a Lada, without a column for every rare brand.

6.9Step 9: missing text

Python, continues from the cells above
df["market"] = df["market"].fillna("unknown")

print(df["market"].value_counts())

Output

market
unknown            2869
Europe             1511
America            1437
official dealer    1147
Korea              1132
Japan               405
Russia              320
other               284
China                89
Dubai                65
Name: count, dtype: int64

For a third of the cars the advert does not say where the car was first sold. "Not said" can itself mean something, so it becomes a category of its own, "unknown". This uses nothing from the other rows, so it can be done before the split.

6.10Step 10: encode

Python, continues from the cells above
text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"]

df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)

print(df.shape)

Output

(9259, 84)

The eight text columns become one-hot columns (Topic 25). is_new, damaged and painted are already 0 and 1. 83 features and the target.

6.11Step 11: split

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["price_azn"])
y = df["price_azn"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(X_train.shape, X_test.shape)

Output

(7407, 83) (1852, 83)

Change it and run: change test_size to 0.3 and run: about 2,780 cars become test data.

7,407 cars for training and 1,852 for the test.

6.12Step 12: fill the missing numbers with the training medians

Python, continues from the cells above
medians = X_train[["horsepower", "seats", "owners"]].median()

X_train = X_train.fillna(medians)
X_test = X_test.fillna(medians)

print(medians)
print(X_train.isna().sum().sum(), X_test.isna().sum().sum())

Output

horsepower    150.0
seats           5.0
owners          1.0
dtype: float64
0 0

fillna(medians) fills each column with its own median. The medians come from the training cars only, and the same numbers fill the test cars: the test data must not help to build the model, not even through a median (Topic 23). That is why this step comes after the split. The median and not the mean: the mean of the horsepower is pulled up by a few very strong cars.

6.13Step 13: no scaling

A forest needs no scaling, and neither does plain linear regression for its predictions (Part 5; Part 9 checks it on the cars). The features stay as they are.

Try it yourself

This task continues from Steps 1 to 3 (the raw file, without its repeated rows). Print the number of missing values of horsepower, then the share of cars with a missing market, rounded to 4 decimals.
Show a hint
df["horsepower"].isna().sum(); the mean of isna() is the share: round(df["market"].isna().mean(), 4).
Show the solution
Python, continues from the cells above
print(df["horsepower"].isna().sum())
print(round(df["market"].isna().mean(), 4))

Output

3281
0.3095

7The random forest

7.1Train and judge

Python, continues from the cells above
from sklearn.ensemble import RandomForestRegressor

forest = RandomForestRegressor(random_state=42)
forest.fit(X_train, y_train)

print(round(forest.score(X_train, y_train), 4))
print(round(forest.score(X_test, y_test), 4))

Output

0.9801
0.8649

Change it and run: write RandomForestRegressor(n_estimators=10, random_state=42) and run: ten trees are already far better than one tree.

RandomForestRegressor lives in sklearn.ensemble, next to the classifier. For a regression model score gives the R². On the training cars it is 0.98: the full trees know their prices. On the test cars it is 0.865: the forest explains about 86 percent of the variance of prices it has never seen.

7.2The measures of regression

Python, continues from the cells above
from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error

predicted = forest.predict(X_test)

print(round(r2_score(y_test, predicted), 4))
print(round(mean_absolute_error(y_test, predicted)))
print(round(root_mean_squared_error(y_test, predicted)))

Output

0.8649
2750
5154

r2_score gives the same number as score. The MAE says that a predicted price is typically about 2,750 AZN away from the true price. The RMSE is almost twice as large: a few cars, mostly expensive ones, have large errors. round(x) without a number of decimals gives a whole number, which is enough for manats.

7.3Inside the forest

Python, continues from the cells above
print(len(forest.estimators_))
print([tree.get_depth() for tree in forest.estimators_[:5]])
print(forest.estimators_[0].get_n_leaves())

Output

100
[35, 34, 32, 33, 31]
4373

100 trees, each an ordinary DecisionTreeRegressor, more than 30 levels deep. The first tree has 4,373 leaves: a bootstrap sample of 7,407 cars holds about 4,700 different cars, and most of them end in a leaf of their own.

7.4How the forest predicts one car

Python, continues from the cells above
car = X_test.iloc[[0]]

prices = [tree.predict(car.values)[0] for tree in forest.estimators_]

print(min(prices), max(prices))
print(round(sum(prices) / len(prices), 1))
print(forest.predict(car))
print(y_test.iloc[0])

Output

9800.0 47500.0
34199.0
[34199.]
42500

Change it and run: change iloc[[0]] to iloc[[5]] and look at the predictions of the trees for another car.

The list prices holds the prediction of each of the 100 trees for the first test car (.values passes the plain numbers: the trees inside the forest were trained without the column names). The trees disagree a lot: their predictions lie between 9,800 and 47,500 AZN. Their mean is exactly what forest.predict gives, and it is much closer to the true price than the worst trees.

7.5How sure is the forest about a car?

The 100 predictions of the trees say more than their mean. When the trees agree, the forest is sure about the price; when they disagree, it is not. The standard deviation of the trees' predictions (Topic 18) measures how much they disagree:

Python, continues from the cells above
import numpy as np

print(round(np.std(prices)))

Output

7460

For the first test car the trees' predictions spread by about 7,460 AZN around their mean: the forest is unsure about this car, and indeed its prediction is far from the true price. For a common car the trees agree much more. This spread is a rough measure of how much to trust one prediction; it is not an exact interval.

010,00020,00030,00040,00050,000
  • one tree
  • the mean: the forest
  • the true price
The predictions of the 100 trees for the first test car, one dot per tree. They spread from 9,800 to 47,500 manats. Their mean, 34,199, is the forest's prediction; the true price is 42,500. A wide spread like this one means that the forest is unsure about the car.

7.6True against predicted prices

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.scatter(y_test, predicted, s=6, alpha=0.5)
plt.plot([0, 160000], [0, 160000], color="gray")
plt.xlabel("true price (AZN)")
plt.ylabel("predicted price (AZN)")
plt.title("Random forest: predicted against true prices")
plt.show()
Chart: Random forest: predicted against true prices

A perfect model would put every car on the grey line. The cheap and middle cars lie close to it; the expensive cars spread out more, and most of them lie below the line: the forest is too careful with them.

7.7The forest cannot go beyond the training prices

Python, continues from the cells above
print(y_train.max())
print(round(predicted.max()))
print((predicted > y_train.max()).sum())

Output

160000
94290
0

The most expensive training car costs 160,000 AZN; the highest prediction for a test car is far below it, and no prediction is above it. This is Part 3 in numbers: a mean of training prices cannot leave their range, and averaging pulls the predictions of rare expensive cars down towards the middle.

7.8Feature importances

Python, continues from the cells above
importances = pd.Series(forest.feature_importances_, index=X.columns)

print(importances.sort_values(ascending=False).head(8).round(3))

Output

year              0.449
engine_l          0.265
horsepower        0.050
mileage_km        0.045
drive_front       0.019
gearbox_manual    0.018
fuel_petrol       0.017
body_sedan        0.015
dtype: float64

For a regression forest the importance of a feature is how much it lowered the squared error, summed over all splits and averaged over the trees. The year and the engine volume lead: a newer car and a larger engine mean a higher price. The horsepower and the mileage come next.

Python, continues from the cells above
import matplotlib.pyplot as plt

importances.sort_values().tail(8).plot(kind="barh")
plt.title("The eight most important features of the forest")
plt.xlabel("importance (decrease of the squared error)")
plt.show()
Chart: The eight most important features of the forest

The warning of Topic 30 holds here too: the impurity importance favours features with many values, such as the mileage. The permutation importance of Topic 30 works for regression in the same way, with the R² instead of the accuracy; with 83 columns it takes long, so it is left out here.

Try it yourself

This task continues from the cells of Parts 6 and 7. Take the second test car (position 1). Print the mean of the 100 trees' predictions for it rounded to 1 decimal, their standard deviation as a whole number, and its true price. Is the forest surer about this car than about the first one?
Show a hint
car = X_test.iloc[[1]], prices = [tree.predict(car.values)[0] for tree in forest.estimators_], then np.mean(prices), np.std(prices) and y_test.iloc[1].
Show the solution
Python, continues from the cells above
import numpy as np

car = X_test.iloc[[1]]
prices = [tree.predict(car.values)[0] for tree in forest.estimators_]

print(round(np.mean(prices), 1))
print(round(np.std(prices)))
print(y_test.iloc[1])

Output

21946.4
2130
19300

8Tuning the forest

8.1n_estimators: how many trees?

The forest's prediction is the mean of its trees. So the forest of the first nn trees can be computed from the trees we already have, without training new forests. First, the predictions of every tree for every test car:

Python, continues from the cells above
import numpy as np

tree_predictions = np.array([tree.predict(X_test.values) for tree in forest.estimators_])

print(tree_predictions.shape)
print(np.allclose(tree_predictions.mean(axis=0), predicted))

Output

(100, 1852)
True

tree_predictions is a table with one row for each of the 100 trees and one column for each of the 1,852 test cars. The mean of each column (axis=0) is exactly the forest's prediction: np.allclose checks that the two arrays are equal up to tiny rounding.

Python, continues from the cells above
for n in [1, 5, 10, 20, 50, 100]:
    mean_of_n = tree_predictions[:n].mean(axis=0)
    print(n, round(r2_score(y_test, mean_of_n), 4))

Output

1 0.7203
5 0.8446
10 0.853
20 0.8598
50 0.862
100 0.8649

tree_predictions[:n] takes the first nn trees. (This is the same as a forest with n_estimators=n and the same random_state, because scikit-learn draws the seeds of the trees one after another.) One tree reaches an R² of 0.72; from 1 to 20 trees the R² rises steeply, and after 50 trees it hardly moves.

The forest of the project with only its first n trees (from 1 to 100): its test R², and its prediction for the first test car.

0.70.80.9120406080100

10 trees: test R² 0.853.

The first test car: the mean of 10 trees is 40,580 AZN; the true price is 42,500 AZN.

After about 50 trees the curve is flat: more trees cost time, not quality, and they never make the forest overfit.

Python, continues from the cells above
import matplotlib.pyplot as plt

sizes = list(range(1, 101))
scores = [r2_score(y_test, tree_predictions[:n].mean(axis=0)) for n in sizes]

plt.plot(sizes, scores)
plt.xlabel("number of trees")
plt.ylabel("test R²")
plt.title("More trees: a rising, then flat curve")
plt.show()
Chart: More trees: a rising, then flat curve

8.2The out-of-bag R²: a free validation

Python, continues from the cells above
oob_forest = RandomForestRegressor(oob_score=True, random_state=42)
oob_forest.fit(X_train, y_train)

print(round(oob_forest.oob_score_, 4))

Output

0.8578

Change it and run: add max_features=0.33 and run: the OOB R² of the tuned setting.

With oob_score=True the forest predicts each training car with the trees for which it was out of bag (about 37 of the 100) and computes the R² of these predictions. It is a little lower than the test R², because each car is predicted by about 37 trees instead of 100, but it is measured without the test data. That makes it the right tool for choosing hyperparameters.

8.3max_features, chosen with the OOB R²

The default forest used max_features=1.0 (OOB R² above). Now three smaller values:

Python, continues from the cells above
for share in [0.5, 0.33, "sqrt"]:
    model = RandomForestRegressor(max_features=share, oob_score=True, random_state=42)
    model.fit(X_train, y_train)
    print(share, round(model.oob_score_, 4))

Output

0.5 0.8616
0.33 0.862
sqrt 0.847

Each line shows the value of max_features and the OOB R². A third of the features (0.33, 27 of the 83 at every split) gives the highest OOB R², just above 0.5; both beat the default 1.0. "sqrt", the default for classes, gives each split only 9 features and is too few here: the year and the engine are missing from too many splits. A smaller max_features also makes the forest faster, because each split tries fewer features.

8.4min_samples_leaf

Python, continues from the cells above
for leaf in [1, 2, 5]:
    model = RandomForestRegressor(max_features=0.33, min_samples_leaf=leaf, oob_score=True, random_state=42)
    model.fit(X_train, y_train)
    print(leaf, round(model.oob_score_, 4))

Output

1 0.862
2 0.8569
5 0.8355

Larger leaves make the OOB R² fall. For prices, a leaf of a single car is best: each limit replaces the price of the most similar car by a mean over several less similar cars. (In Topic 30 larger leaves helped the AUC of the bank forest: what helps depends on the data, and the OOB score or cross-validation decides.)

8.5The tuned forest

Python, continues from the cells above
tuned = RandomForestRegressor(max_features=0.33, random_state=42)
tuned.fit(X_train, y_train)

tuned_predicted = tuned.predict(X_test)

print(round(r2_score(y_test, tuned_predicted), 4))
print(round(mean_absolute_error(y_test, tuned_predicted)))
print(round(root_mean_squared_error(y_test, tuned_predicted)))

Output

0.8733
2700
4992

Change it and run: change max_features=0.33 to max_features=0.5 and run.

On the test cars, chosen without them, the tuned forest is better on all three measures than the default forest: a higher R², a smaller MAE and a smaller RMSE.

8.6Why it is better: less correlated trees

The variance formula says that a forest gains by making its trees less alike. As in Topic 30, the correlation of every pair of trees can be measured from their predictions:

Python, continues from the cells above
tuned_predictions = np.array([tree.predict(X_test.values) for tree in tuned.estimators_])

default_corr = np.corrcoef(tree_predictions)
tuned_corr = np.corrcoef(tuned_predictions)

print(round((default_corr.sum() - 100) / (100 * 99), 3))
print(round((tuned_corr.sum() - 100) / (100 * 99), 3))

Output

0.87
0.819

np.corrcoef gives a 100×100100 \times 100 table of the correlations of every pair of trees; without the 100 ones on its diagonal, sum−100100×99\frac{\text{sum} - 100}{100 \times 99} is the mean over the pairs. The trees of the default forest, which all see every feature, are correlated with about 0.87; with a third of the features at each split, about 0.82. The prices of cars are dominated by the year and the engine, so all trees stay quite alike; the random features make them a little less so, and that is enough to lower the variance of their mean.

Try it yourself

This task continues from the cells of Parts 6 to 8. The last 50 trees of the forest are a forest of their own. Print the test R² of the mean of trees 51 to 100 (tree_predictions[50:]), rounded to 4 decimals. Is it close to the R² of the first 50 trees, 0.862?
Show a hint
tree_predictions[50:].mean(axis=0) is their prediction for every test car; then r2_score(y_test, ...).
Show the solution
Python, continues from the cells above
print(round(r2_score(y_test, tree_predictions[50:].mean(axis=0)), 4))

Output

0.8653

Try it yourself

This task continues from the cells of Parts 6 and 7. Train a forest with max_features=0.33, max_depth=15, oob_score=True and random_state=42. Print its OOB R², rounded to 4 decimals. Is it better than 0.862, the same forest without a depth limit?
Show a hint
model = RandomForestRegressor(max_features=0.33, max_depth=15, oob_score=True, random_state=42), fit, then model.oob_score_.
Show the solution
Python, continues from the cells above
model = RandomForestRegressor(max_features=0.33, max_depth=15, oob_score=True, random_state=42)
model.fit(X_train, y_train)

print(round(model.oob_score_, 4))

Output

0.8593

9Bagging around any regression model

9.1Bagging for regression

Bagging is the same as in Topic 30 (Part 9): draw many bootstrap samples, train the same model on each, and combine. For a number the answers are combined by their mean. In scikit-learn it is BaggingRegressor from sklearn.ensemble, with the hyperparameters of BaggingClassifier:

Bagging for regression
HyperparameterDefaultRole
estimatora decision treethe model inside, trained on every sample
n_estimators10how many models (and bootstrap samples)
max_samples1.0the size of each sample, as a share or a number of rows
max_features1.0the share of the features each model gets (one random set per model, not per split)
bootstrapTruedraw the rows with replacement
oob_scoreFalsethe out-of-bag R²
random_stateNonethe seed for the samples

9.2Bagging around a full decision tree

Python, continues from the cells above
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor

full_tree = DecisionTreeRegressor(random_state=42)
full_tree.fit(X_train, y_train)

bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42)
bagged_trees.fit(X_train, y_train)

print(round(full_tree.score(X_train, y_train), 4), round(full_tree.score(X_test, y_test), 4))
print(round(bagged_trees.score(X_test, y_test), 4))
print(round(forest.score(X_test, y_test), 4))

Output

0.9996 0.7958
0.8654
0.8649

One full tree: an R² of almost 1 on the training cars and about 0.80 on the test cars, the overfitting of Part 2. A hundred bagged full trees: about 0.865 on the test cars. The third line is the default random forest: practically the same score as the bagged trees, because with max_features=1.0 it is bagging of trees. (The two are not equal to the last digit: they draw their random numbers differently.) The tuned forest beats both with its random features.

9.3Bagging around a shallow tree

Python, continues from the cells above
shallow = DecisionTreeRegressor(max_depth=8, random_state=42)
shallow.fit(X_train, y_train)

bagged_shallow = BaggingRegressor(estimator=DecisionTreeRegressor(max_depth=8), n_estimators=100, random_state=42)
bagged_shallow.fit(X_train, y_train)

print(round(shallow.score(X_test, y_test), 4), round(bagged_shallow.score(X_test, y_test), 4))

Output

0.7805 0.8318

Change it and run: change both max_depth=8 to max_depth=4 and run: the bias of the shallower tree grows.

A tree of depth 8 has at most 256 leaves, so it can predict at most 256 different prices. Bagging 100 of them gives a much finer set of prices and a clearly higher R². Still, it stays below the bagged full trees: a depth of 8 is too little for the variety of cars, and averaging cannot remove bias.

9.4Bagging around linear regression

Bagging works around any regression model. Plain linear regression (Topic 22) needs the encoded and filled data we have. Does it need scaling? Topic 24 said no: scaling changes its weights, not its predictions. A quick check on the cars, with a StandardScaler fitted on the training data:

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

plain = LinearRegression().fit(X_train, y_train)
scaled = LinearRegression().fit(X_train_scaled, y_train)

print(round(plain.score(X_test, y_test), 4), round(scaled.score(X_test_scaled, y_test), 4))

Output

0.7124 0.7124

The same R² with and without scaling, so the project goes on without it: one set of data serves every model of this part.

Python, continues from the cells above
linear = LinearRegression()
linear.fit(X_train, y_train)

bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)
bagged_linear.fit(X_train, y_train)

print(round(linear.score(X_test, y_test), 4), round(bagged_linear.score(X_test, y_test), 4))

Output

0.7124 0.7117

The same R² twice, about 0.71. Every bootstrap sample of 7,407 cars gives almost the same weights, so the mean of 100 linear regressions is the same linear regression again. Bagging cures variance, and linear regression has little of it. Its problem is bias: a price is not a straight-line sum of the features (the price falls fast in the first years of a car and slowly later), and no averaging changes that. The trees can follow such curves; that is why all tree models beat it here.

9.5A relative: extremely randomized trees

Python, continues from the cells above
from sklearn.ensemble import ExtraTreesRegressor

extra = ExtraTreesRegressor(random_state=42)
extra.fit(X_train, y_train)

print(round(extra.score(X_test, y_test), 4))

Output

0.87

Extremely randomized trees (Topic 30, Part 9) draw the thresholds at random too, and train every tree on all rows. On the cars they are about as good as the tuned forest, without any tuning. It is one more model of the same family worth trying.

9.6The scores of every model

Python, continues from the cells above
models = [
    ("full tree", full_tree),
    ("tree, max_depth=8", shallow),
    ("bagged full trees", bagged_trees),
    ("bagged trees, max_depth=8", bagged_shallow),
    ("random forest", forest),
    ("tuned random forest", tuned),
    ("extremely randomized trees", extra),
    ("linear regression", linear),
    ("bagged linear regression", bagged_linear),
]

for name, model in models:
    model_predicted = model.predict(X_test)
    r2 = round(r2_score(y_test, model_predicted), 4)
    mae = round(mean_absolute_error(y_test, model_predicted))
    rmse = round(root_mean_squared_error(y_test, model_predicted))
    print(name, r2, mae, rmse)

Output

full tree 0.7958 3508 6337
tree, max_depth=8 0.7805 3768 6569
bagged full trees 0.8654 2757 5143
bagged trees, max_depth=8 0.8318 3294 5750
random forest 0.8649 2750 5154
tuned random forest 0.8733 2700 4992
extremely randomized trees 0.87 2681 5055
linear regression 0.7124 4640 7519
bagged linear regression 0.7117 4647 7529

Every line shows a model, its R², its MAE and its RMSE on the same 1,852 test cars. No model needs other test data here: nothing was scaled.

Python, continues from the cells above
import matplotlib.pyplot as plt

names = [name for name, model in models]
r2s = [r2_score(y_test, model.predict(X_test)) for name, model in models]

plt.barh(names, r2s)
plt.xlim(0.6, 0.9)
plt.xlabel("test R²")
plt.title("Single models, bagged models and forests")
plt.show()
Chart: Single models, bagged models and forests

What the comparison shows:

  • Bagging lifts the unstable full tree from about 0.80 to about 0.865.
  • Bagging helps the shallow tree too, but its bias stays.
  • Bagging does nothing for the stable linear regression.
  • The default random forest is bagging of trees and scores the same; the tuned forest, with a third of the features at every split, is the best, together with the extremely randomized trees.

Try it yourself

This task continues from the cells of Part 6. Train a BaggingRegressor of 100 full trees with oob_score=True and random_state=42. Print its OOB R², then its test R², each rounded to 4 decimals. Compare the OOB R² with the default forest's 0.8578.
Show a hint
model = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, oob_score=True, random_state=42), fit, then model.oob_score_ and model.score(X_test, y_test).
Show the solution
Python, continues from the cells above
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor

model = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, oob_score=True, random_state=42)
model.fit(X_train, y_train)

print(round(model.oob_score_, 4))
print(round(model.score(X_test, y_test), 4))

Output

0.8567
0.8654

10The workflow, step by step

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns10,000 adverts, 19 columns
2. Checkmissing values, repeated rowsfour columns with gaps, 691 repeated rows
3. Repeated rowsdrop them before the split9,309 rows left
4. Impossible valuesfind them with describe()year 0, three million kilometres; engine 0 is right for electric cars
5. Removethe rows with impossible values9,259 rows left
6. Too many categoriesdrop or groupmodel (816 values) dropped
7. Targetits distribution and its outliersreal expensive cars, kept
8. Rare categoriesgroup thembrands with fewer than 50 cars become "other"
9. Missing texta category of its ownmarket: "unknown"
10. Encodetext to numbersone-hot: 83 features
11. Splittraining and test data7,407 and 1,852
12. Missing numbersfill with the training medians, after the splithorsepower, seats, owners
13. Scaleonly for the models that need itnot for the forest, not for plain linear regression
14. Modelthe random forestdefault: test R² 0.865
15. Look insidetrees, one car, importances, the range of the predictionsyear and engine lead; no prediction above the training prices
16. Tunen_estimators, max_features and min_samples_leaf with the OOB R²max_features=0.33
17. Model againbagging around other modelstrees gain, linear regression does not
18. JudgeR², MAE and RMSE of every model on the same test datathe tuned forest and the extremely randomized trees lead

Try it yourself

(a) Which comes first: dropping the repeated rows or the split? (b) On which data are the medians for the missing values computed? (c) For which models of this project were the features scaled? (d) Which model had the highest R²?

Show a hint
Look at Steps 3, 12, 13 and 18 of the table.
Show the solution

Answer: (a) dropping the repeated rows; (b) the training data; (c) none; (d) the tuned random forest.

A copy in both parts would make the test score too good, and a median of all rows would let the test data help to build the model. No model of this project needs scaling: trees never do, and plain linear regression predicts the same with and without it.

11Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Keeping repeated rows.The same car in the training and the test data makes the test score too good.drop_duplicates() before the split.
Filling missing values with medians of all the data.The test data then helps to build the model.Compute the medians on the training data, after the split.
Treating a year 0 as an outlier to keep.It is a mistake in the data, not a rare car.Remove such rows or set the value to missing.
One-hot encoding a column with hundreds of categories.Hundreds of columns, most with one or two cars.Drop it, or group its rare values.
Thinking RandomForestRegressor() uses random features.Its default max_features=1.0 is plain bagging of trees.Tune max_features: try 0.33, 0.5, "sqrt".
Expecting a forest to predict above the highest training price.Every leaf predicts a mean of training prices.Know the range; use a model that extrapolates when needed.
Judging a forest on its training R².Its full trees know the training prices by heart.The test R² or the OOB R².
Reading the RMSE as the typical error.Large errors count much more in it.The MAE is the typical error; the RMSE shows the large ones.
Choosing max_features with the test data.The test data then helps to build the model.The OOB R² or cross-validation.
Expecting bagging to improve linear regression.It cures variance; linear regression has little.Bag unstable models, such as deep trees.
Scaling the features for a forest.It changes nothing.Scale only for models that need it.
Using accuracy or recall for prices.They are measures for classes.R², MAE, RMSE.

12Solved problems

The first four problems are short and solved by hand. Problems 5 to 16 are one project on car_prices.csv, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.

Problem 1: The best split

Four cars have the mileages 20, 60, 120 and 180 thousand km and the prices 30, 26, 14 and 10 thousand AZN. (a) What is the squared error of the node with all four cars? (b) Which threshold of the mileage gives the lowest error after the split, and what do its two leaves predict?

Idea. The squared error of a node and the weighted error after a split (Part 2). The thresholds lie halfway: 40, 90 and 150.

mean=30+26+14+104=804=20squared error=102+62+62+1024=2724=68\begin{aligned} \text{mean} &= \frac{30 + 26 + 14 + 10}{4} = \frac{80}{4} = 20 \\[8pt] \text{squared error} &= \frac{10^2 + 6^2 + 6^2 + 10^2}{4} \\[4pt] &= \frac{272}{4} = 68 \end{aligned}

For the threshold 90:

left mean=30+262=28left error=22+222=4right mean=14+102=12right error=22+222=4after the split=24×4+24×4=4\begin{aligned} \text{left mean} &= \frac{30 + 26}{2} = 28 \\[6pt] \text{left error} &= \frac{2^2 + 2^2}{2} = 4 \\[10pt] \text{right mean} &= \frac{14 + 10}{2} = 12 \\[6pt] \text{right error} &= \frac{2^2 + 2^2}{2} = 4 \\[10pt] \text{after the split} &= \tfrac{2}{4} \times 4 + \tfrac{2}{4} \times 4 = 4 \end{aligned}

For the threshold 40:

left error=0(one car)right mean=26+14+103=16.667right error=46.222after the split=14×0+34×46.222=34.667\begin{aligned} \text{left error} &= 0 \quad (\text{one car}) \\[6pt] \text{right mean} &= \frac{26 + 14 + 10}{3} = 16.667 \\[6pt] \text{right error} &= 46.222 \\[10pt] \text{after the split} &= \tfrac{1}{4} \times 0 + \tfrac{3}{4} \times 46.222 \\[4pt] &= 34.667 \end{aligned}

Why: the threshold 150 gives 34.667 as well (by symmetry). The tree chooses mileage ≤ 90, which lowers the error from 68 to 4; its leaves predict 28 thousand AZN for the cars with less mileage and 12 thousand for the others.

Problem 2: The prediction of a forest

A forest of four trees predicts the prices 15,200, 16,800, 14,900 and 17,100 AZN for a car. (a) What does the forest predict? (b) The most expensive training car cost 90,000 AZN. Can this forest ever predict 95,000 AZN?

Idea. The mean of the trees' predictions; every leaf is a mean of training prices (Part 3).

prediction=15,200+16,800+14,900+17,1004=64,0004=16,000 AZN\begin{aligned} & \text{prediction} \\[4pt] &= \frac{15{,}200 + 16{,}800 + 14{,}900 + 17{,}100}{4} \\[4pt] &= \frac{64{,}000}{4} = 16{,}000 \text{ AZN} \end{aligned}

Why: (a) 16,000 AZN. (b) No: no leaf can predict more than 90,000 AZN, and a mean of such predictions cannot either.

Problem 3: The three measures

Three cars cost 10, 20 and 30 thousand AZN; a model predicts 12, 18 and 33. Compute the MAE, the RMSE and the R².

Idea. The formulas of Part 5. The errors y−y^y - \hat{y} are −2-2, 22 and −3-3.

MAE=2+2+33=73=2.333RMSE=4+4+93=5.667=2.381\begin{aligned} \text{MAE} &= \frac{2 + 2 + 3}{3} = \frac{7}{3} = 2.333 \\[8pt] \text{RMSE} &= \sqrt{\frac{4 + 4 + 9}{3}} = \sqrt{5.667} = 2.381 \end{aligned}
yˉ=10+20+303=20∑(y−yˉ)2=102+02+102=200R2=1−17200=1−0.085=0.915\begin{aligned} \bar{y} &= \frac{10 + 20 + 30}{3} = 20 \\[8pt] \textstyle\sum (y - \bar{y})^2 &= 10^2 + 0^2 + 10^2 = 200 \\[8pt] R^2 &= 1 - \frac{17}{200} = 1 - 0.085 = 0.915 \end{aligned}

Why: the typical error is 2,333 AZN; the RMSE is a little larger, because the error of 3 counts more when squared; the model explains 91.5 percent of the variance of the three prices.

Problem 4: Features at a split

The car data has 83 features. How many features does each split of a RandomForestRegressor try (a) with the default settings, (b) with max_features=0.33, (c) with max_features="sqrt"?

Idea. A share is multiplied by the number of features and rounded down; "sqrt" takes the square root, rounded down (Part 4).

0.33×83=27.39, rounded down: 2783=9.11, rounded down: 9\begin{aligned} 0.33 \times 83 &= 27.39, \ \text{rounded down: } 27 \\[6pt] \sqrt{83} &= 9.11, \ \text{rounded down: } 9 \end{aligned}

Why: (a) all 83: the default 1.0 is bagging of trees; (b) 27; (c) 9.

Problem 5: Read and check

Read the file. Print its shape, the number of repeated rows, and the number of missing values in each column.

Idea. The first steps of the workflow (Part 6).

Python
import pandas as pd

df = pd.read_csv("car_prices.csv")

print(df.shape)
print(df.duplicated().sum())
print(df.isna().sum())

Output

(10000, 19)
691
brand            0
model            0
year             0
engine_l         0
horsepower    3457
fuel             0
mileage_km       0
gearbox          0
drive            0
body             0
colour           0
seats         2553
owners        3138
is_new           0
damaged          0
painted          0
market        3092
city             0
price_azn        0
dtype: int64

Why: 691 repeated adverts to drop, and four columns with gaps to fill.

Problem 6: Repeated and impossible rows

Drop the repeated rows, then keep only the cars made in 1950 or later and with at most 1,000,000 km. Print the shape.

Idea. Repeated rows make the test score too good; impossible values are mistakes (Part 6).

Python, continues from the cells above
df = df.drop_duplicates()
df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]

print(df.shape)

Output

(9259, 19)

Why: 741 rows fewer than the file: 691 copies and 50 impossible adverts.

Problem 7: Categories

Drop the column model, group the brands with fewer than 50 cars as "other", and fill the missing market with "unknown". Print the number of brand values and the number of cars with an unknown market.

Idea. Too many categories and missing text (Part 6).

Python, continues from the cells above
df = df.drop(columns=["model"])

counts = df["brand"].value_counts()
rare = counts[counts < 50].index
df.loc[df["brand"].isin(rare), "brand"] = "other"

df["market"] = df["market"].fillna("unknown")

print(df["brand"].nunique())
print((df["market"] == "unknown").sum())

Output

19
2869

Why: 19 brand values instead of more than a hundred, and the unknown market becomes a category of its own.

Problem 8: Encode and split

One-hot encode the eight text columns with drop_first=True and dtype=int. Make X and yy and split them with test_size=0.25 and random_state=7. Print the shapes of X_train and X_test.

Idea. Text to numbers, then the split (Part 6).

Python, continues from the cells above
from sklearn.model_selection import train_test_split

text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"]
df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)

X = df.drop(columns=["price_azn"])
y = df["price_azn"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)

print(X_train.shape, X_test.shape)

Output

(6944, 83) (2315, 83)

Why: 83 features; a quarter of the cars is kept for the test.

Problem 9: Fill the missing numbers

Fill horsepower, seats and owners in both parts with the medians of the training data. Print the medians and the number of missing values left in X_train and X_test.

Idea. Medians from the training data only, after the split (Part 6).

Python, continues from the cells above
medians = X_train[["horsepower", "seats", "owners"]].median()

X_train = X_train.fillna(medians)
X_test = X_test.fillna(medians)

print(medians)
print(X_train.isna().sum().sum(), X_test.isna().sum().sum())

Output

horsepower    150.0
seats           5.0
owners          1.0
dtype: float64
0 0

Why: no gaps are left, and the test cars were filled with numbers they did not help to compute.

Problem 10: A random forest

Train a RandomForestRegressor with random_state=42. Print its training R² and its test R², rounded to 4 decimals.

Idea. The default forest of Part 7; score gives the R².

Python, continues from the cells above
from sklearn.ensemble import RandomForestRegressor

forest = RandomForestRegressor(random_state=42)
forest.fit(X_train, y_train)

print(round(forest.score(X_train, y_train), 4))
print(round(forest.score(X_test, y_test), 4))

Output

0.9817
0.8377

Why: almost perfect on the training cars, as its full trees are; the test R² is the honest score.

Problem 11: Its errors in manats

Print the MAE and the RMSE of the forest on the test data, as whole numbers.

Idea. The measures of regression (Part 5).

Python, continues from the cells above
from sklearn.metrics import r2_score, mean_absolute_error, root_mean_squared_error

predicted = forest.predict(X_test)

print(round(mean_absolute_error(y_test, predicted)))
print(round(root_mean_squared_error(y_test, predicted)))

Output

2881
5996

Why: the typical error is under 3,000 AZN, and the RMSE, about twice as large, shows that a few cars have large errors.

Problem 12: The trees for one car

For the first test car, compute the prediction of every tree of the forest. Print the mean of the 100 predictions rounded to 1 decimal, and the forest's own prediction.

Idea. The forest predicts the mean of its trees (Part 7).

Python, continues from the cells above
car = X_test.iloc[[0]]

prices = [tree.predict(car.values)[0] for tree in forest.estimators_]

print(round(sum(prices) / len(prices), 1))
print(forest.predict(car))

Output

24579.0
[24579.]

Why: the same number twice: the forest is the mean of its trees.

Problem 13: The OOB R² of three forests

For max_features equal to 1.0, 0.33 and "sqrt", train a forest with oob_score=True and random_state=42, and print the value and the OOB R² rounded to 4 decimals.

Idea. The out-of-bag R² chooses a hyperparameter without the test data (Part 8).

Python, continues from the cells above
for share in [1.0, 0.33, "sqrt"]:
    model = RandomForestRegressor(max_features=share, oob_score=True, random_state=42)
    model.fit(X_train, y_train)
    print(share, round(model.oob_score_, 4))

Output

1.0 0.8695
0.33 0.8673
sqrt 0.8473

Why: with this split 1.0 and 0.33 are almost equal, and "sqrt" is clearly worse: the best value depends on the data, and the OOB score shows it at no cost.

Problem 14: The tuned forest

Train a forest with max_features=0.33 and random_state=42, called tuned. Print its test R² rounded to 4 decimals, its MAE and its RMSE as whole numbers.

Idea. The setting chosen in the lesson (Part 8).

Python, continues from the cells above
tuned = RandomForestRegressor(max_features=0.33, random_state=42)
tuned.fit(X_train, y_train)

tuned_predicted = tuned.predict(X_test)

print(round(r2_score(y_test, tuned_predicted), 4))
print(round(mean_absolute_error(y_test, tuned_predicted)))
print(round(root_mean_squared_error(y_test, tuned_predicted)))

Output

0.8459
2928
5842

Why: a higher R² and a smaller RMSE than the default forest on this split too (the MAE is about the same), even though its OOB R² was a little lower than that of 1.0: the OOB R² is an estimate, and values this close may change order on the test data. Both ways of judging agree that "sqrt" is too few.

Problem 15: Bagged trees

Train a single full DecisionTreeRegressor with random_state=42 and a BaggingRegressor of 100 full trees with random_state=42. Print the test R² of each, rounded to 4 decimals.

Idea. Bagging around an unstable model (Part 9).

Python, continues from the cells above
from sklearn.ensemble import BaggingRegressor
from sklearn.tree import DecisionTreeRegressor

full_tree = DecisionTreeRegressor(random_state=42)
full_tree.fit(X_train, y_train)

bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42)
bagged_trees.fit(X_train, y_train)

print(round(full_tree.score(X_test, y_test), 4))
print(round(bagged_trees.score(X_test, y_test), 4))

Output

0.7603
0.8373

Why: one full tree is far behind; the bagged trees score like the default forest, which is bagging of trees.

Problem 16: Bagged linear regression

Train a LinearRegression and a BaggingRegressor of 100 linear regressions with random_state=42. Print the test R² of each, rounded to 4 decimals.

Idea. Bagging around a stable model; plain linear regression needs no scaling (Part 9).

Python, continues from the cells above
from sklearn.ensemble import BaggingRegressor
from sklearn.linear_model import LinearRegression

linear = LinearRegression()
linear.fit(X_train, y_train)

bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)
bagged_linear.fit(X_train, y_train)

print(round(linear.score(X_test, y_test), 4))
print(round(bagged_linear.score(X_test, y_test), 4))

Output

0.6981
0.6986

Why: almost the same number twice: bagging cannot improve a model that hardly changes from sample to sample.

13Practice

Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on car_prices.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the raw file to bagged models. Under every problem there is a hint and a solution.

13.1Group A: by hand

  1. 1.Four cars were made in 2010, 2013, 2018 and 2021 and cost 9, 11, 25 and 29 thousand AZN. (a) What is the error after the split "year ≤ 2015.5"? (b) What do its two leaves predict?

    Show a hint
    The squared error of each side around its mean, then weighted by the share of the cars.
    Show one possible solution

    Answer: (a) 2.5; (b) 10 and 27 thousand AZN.

    left mean=9+112=10left error=12+122=1right mean=25+292=27right error=22+222=4after the split=24×1+24×4=0.5+2=2.5\begin{aligned} \text{left mean} &= \frac{9 + 11}{2} = 10 \\[6pt] \text{left error} &= \frac{1^2 + 1^2}{2} = 1 \\[10pt] \text{right mean} &= \frac{25 + 29}{2} = 27 \\[6pt] \text{right error} &= \frac{2^2 + 2^2}{2} = 4 \\[10pt] \text{after the split} &= \tfrac{2}{4} \times 1 + \tfrac{2}{4} \times 4 \\[4pt] &= 0.5 + 2 = 2.5 \end{aligned}

    The leaves predict their means, 10 and 27.

  2. 2.Five trees predict 20, 22, 19, 25 and 24 thousand AZN for a car. (a) What does the forest predict? (b) The car really costs 23 thousand AZN. How large is the error of the forest?

    Show a hint
    The mean of the five predictions.
    Show one possible solution

    Answer: (a) 22 thousand AZN; (b) 1 thousand AZN.

    forest=20+22+19+25+245=1105=22error=23−22=1\begin{aligned} \text{forest} &= \frac{20 + 22 + 19 + 25 + 24}{5} = \frac{110}{5} = 22 \\[6pt] \text{error} &= 23 - 22 = 1 \end{aligned}
  3. 3.Four cars cost 10, 14, 18 and 22 thousand AZN; a model predicts 11, 13, 20 and 22. Compute the MAE, the RMSE (3 decimals) and the R² (3 decimals).

    Show a hint
    The errors are −1-1, 11, −2-2 and 00; the mean of the true prices is 16.
    Show one possible solution

    Answer: MAE 1; RMSE 1.225; R² 0.925.

    MAE=1+1+2+04=1RMSE=1+1+4+04=1.5=1.225∑(y−yˉ)2=36+4+4+36=80R2=1−680=1−0.075=0.925\begin{aligned} \text{MAE} &= \frac{1 + 1 + 2 + 0}{4} = 1 \\[6pt] \text{RMSE} &= \sqrt{\frac{1 + 1 + 4 + 0}{4}} \\[4pt] &= \sqrt{1.5} = 1.225 \\[8pt] \textstyle\sum (y - \bar{y})^2 &= 36 + 4 + 4 + 36 = 80 \\[6pt] R^2 &= 1 - \frac{6}{80} = 1 - 0.075 = 0.925 \end{aligned}
  4. 4.(a) A data set has 60 features. How many features does each split of RandomForestRegressor try by default, and with max_features=0.5? (b) Does bagging help plain linear regression much? (c) A forest was trained on cars up to 90,000 AZN. Can it predict 120,000 AZN?

    Show a hint
    The default share is 1.0; bagging cures variance; a leaf predicts a mean of training prices.
    Show one possible solution

    Answer: (a) 60 and 30; (b) no; (c) no.

    1.0×60=60,0.5×60=301.0 \times 60 = 60, \qquad 0.5 \times 60 = 30

    Linear regression is stable, so its bagged copies are almost the same model. Every leaf predicts a mean of training prices, at most 90,000 AZN.

13.2Group B: one project in Python

The same workflow as in the lesson, on the same raw file, with another split: test_size=0.3 with random_state=1, and a forest tuned with max_features=0.5, the best value of the OOB R² for this split. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.

Steps 5 to 8: from the raw file to the encoded table

Read the file, drop the copies and the impossible rows, the categories, the encoding.

  1. 5.Read car_prices.csv into df. Print the shape, then the number of repeated rows.
    Show a hint
    df = pd.read_csv("car_prices.csv"), then print(df.shape) and print(df.duplicated().sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("car_prices.csv")
    
    print(df.shape)
    print(df.duplicated().sum())

    Output

    (10000, 19)
    691
  2. 6.Drop the repeated rows, then keep only the cars made in 1950 or later and with at most 1,000,000 km. Print the number of rows. This step continues from Step 5.
    Show a hint
    df = df.drop_duplicates(), then df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)], then print(len(df)).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop_duplicates()
    df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)]
    
    print(len(df))

    Output

    9259
  3. 7.Drop the column model, group the brands with fewer than 50 cars as "other", and fill the missing market with "unknown". Print the number of cars whose brand is now "other".
    Show a hint
    counts = df["brand"].value_counts(), rare = counts[counts < 50].index, df.loc[df["brand"].isin(rare), "brand"] = "other"; then print((df["brand"] == "other").sum()).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop(columns=["model"])
    
    counts = df["brand"].value_counts()
    rare = counts[counts < 50].index
    df.loc[df["brand"].isin(rare), "brand"] = "other"
    
    df["market"] = df["market"].fillna("unknown")
    
    print((df["brand"] == "other").sum())

    Output

    864
  4. 8.One-hot encode the eight text columns of text_columns with drop_first=True and dtype=int. Print the number of columns.
    Show a hint
    df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int), then print(len(df.columns)).
    Show one possible solution
    Python, continues from the cells above
    text_columns = ["brand", "fuel", "gearbox", "drive", "body", "colour", "market", "city"]
    df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int)
    
    print(len(df.columns))

    Output

    84

Steps 9 to 12: split, fill, the random forest and its errors

The split, the training medians, the default forest, the MAE and the RMSE.

  1. 9.Make X (all columns without price_azn) and y. Split them with test_size=0.3 and random_state=1. Print the number of test cars, then their mean price rounded to 1 decimal.
    Show a hint
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1), then len(y_test) and round(y_test.mean(), 1).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["price_azn"])
    y = df["price_azn"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    print(len(y_test))
    print(round(y_test.mean(), 1))

    Output

    2778
    23117.4
  2. 10.Fill horsepower, seats and owners in X_train and X_test with the medians of the training data. Print the median of horsepower, then the number of missing values left in X_test.
    Show a hint
    medians = X_train[["horsepower", "seats", "owners"]].median(), then X_train = X_train.fillna(medians) and the same for X_test; medians["horsepower"] and X_test.isna().sum().sum().
    Show one possible solution
    Python, continues from the cells above
    medians = X_train[["horsepower", "seats", "owners"]].median()
    
    X_train = X_train.fillna(medians)
    X_test = X_test.fillna(medians)
    
    print(medians["horsepower"])
    print(X_test.isna().sum().sum())

    Output

    150.0
    0
  3. 11.Train a RandomForestRegressor called forest with random_state=42. Print its test R², rounded to 4 decimals.
    Show a hint
    forest = RandomForestRegressor(random_state=42), forest.fit(X_train, y_train), then forest.score(X_test, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.ensemble import RandomForestRegressor
    
    forest = RandomForestRegressor(random_state=42)
    forest.fit(X_train, y_train)
    
    print(round(forest.score(X_test, y_test), 4))

    Output

    0.8589
  4. 12.Put the predictions of forest for the test cars into predicted. Print the MAE and the RMSE as whole numbers.
    Show a hint
    predicted = forest.predict(X_test), then round(mean_absolute_error(y_test, predicted)) and the same with root_mean_squared_error.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import mean_absolute_error, root_mean_squared_error
    
    predicted = forest.predict(X_test)
    
    print(round(mean_absolute_error(y_test, predicted)))
    print(round(root_mean_squared_error(y_test, predicted)))

    Output

    2709
    5113

Steps 13 to 16: OOB, tuning, bagging and the scores

The out-of-bag R², a tuned forest, bagged trees, and bagged linear regression with a chart.

  1. 13.Train a forest with max_features=0.5, oob_score=True and random_state=42. Print its OOB R², rounded to 4 decimals.
    Show a hint
    model = RandomForestRegressor(max_features=0.5, oob_score=True, random_state=42), fit, then model.oob_score_.
    Show one possible solution
    Python, continues from the cells above
    oob_forest = RandomForestRegressor(max_features=0.5, oob_score=True, random_state=42)
    oob_forest.fit(X_train, y_train)
    
    print(round(oob_forest.oob_score_, 4))

    Output

    0.8615
  2. 14.Train a forest called tuned with max_features=0.5 and random_state=42. Print its test R² rounded to 4 decimals, then the name of its most important feature.
    Show a hint
    tuned.score(X_test, y_test); pd.Series(tuned.feature_importances_, index=X.columns).idxmax().
    Show one possible solution
    Python, continues from the cells above
    tuned = RandomForestRegressor(max_features=0.5, random_state=42)
    tuned.fit(X_train, y_train)
    
    print(round(tuned.score(X_test, y_test), 4))
    print(pd.Series(tuned.feature_importances_, index=X.columns).idxmax())

    Output

    0.8646
    year
  3. 15.Train a BaggingRegressor of 100 full decision trees with random_state=42, called bagged_trees. Print its test R², rounded to 4 decimals.
    Show a hint
    bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42), fit, then score.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.ensemble import BaggingRegressor
    from sklearn.tree import DecisionTreeRegressor
    
    bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42)
    bagged_trees.fit(X_train, y_train)
    
    print(round(bagged_trees.score(X_test, y_test), 4))

    Output

    0.8581
  4. 16.Train a BaggingRegressor of 100 linear regressions with random_state=42 and print its test R², rounded to 4 decimals. Then draw the test R² of forest, tuned, bagged_trees and the bagged linear regression as horizontal bars.
    Show a hint
    BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42) on X_train (no scaling needed); a list of four names, a list of four scores, plt.barh(names, r2s) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import matplotlib.pyplot as plt
    from sklearn.linear_model import LinearRegression
    
    bagged_linear = BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)
    bagged_linear.fit(X_train, y_train)
    
    print(round(bagged_linear.score(X_test, y_test), 4))
    
    names = ["random forest", "tuned forest", "bagged trees", "bagged linear regression"]
    r2s = [
        forest.score(X_test, y_test),
        tuned.score(X_test, y_test),
        bagged_trees.score(X_test, y_test),
        bagged_linear.score(X_test, y_test),
    ]
    
    plt.barh(names, r2s)
    plt.xlabel("test R²")
    plt.show()

    Output

    0.7037
    The chart this code draws

14Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.How does a regression tree choose the question at a node?

Question 2

2.What does a leaf of a regression tree predict?

Question 3

3.How does RandomForestRegressor combine its trees?

Question 4

4.What is RandomForestRegressor() with its default settings?

Question 5

5.The most expensive training car cost 160,000 AZN. What is the highest price the forest can predict?

Question 6

6.Why are the medians for the missing values computed on the training data only?

Question 7

7.Why are the repeated rows dropped before the split?

Question 8

8.Which measure is in manats and lets large errors count much more?

Question 9

9.Bagging around linear regression gave the same R² as one linear regression. Why?

Question 10

10.What does oob_score_ hold for a RandomForestRegressor?

Question 11

11.Which preprocessing step does a regression forest not need?

Question 12

12.The RMSE of a model is almost twice its MAE. What does this say?

0 of 12 answered.

15Summary

Summary
Formula or ruleMeaning
Squared error of a nodemean of (y−yˉ)2(y - \bar{y})^2how far the values of a node lie from their mean
Error after a splitnleftn×errorleft+nrightn×errorright\tfrac{n_{\text{left}}}{n} \times \text{error}_{\text{left}} + \tfrac{n_{\text{right}}}{n} \times \text{error}_{\text{right}}the tree takes the split with the smallest value
A leaf predictsthe mean of its training valuesnever outside the training range
The forest predictsthe mean of the trees' predictionsno vote, no threshold
MAEmean of ∣y−y^∣\lvert y - \hat{y} \rvertthe typical error, in manats
RMSEmean of (y−y^)2\sqrt{\text{mean of } (y - \hat{y})^2}large errors count more; at least the MAE
R²1−∑(y−y^)2∑(y−yˉ)21 - \frac{\sum (y - \hat{y})^2}{\sum (y - \bar{y})^2}the share of the variance explained
Default max_features1.0 for regressionthe default regression forest is bagging of trees
Summary
CodeWhat it does
RandomForestRegressor(random_state=42)a forest of 100 full regression trees
max_features=0.33a third of the features at every split: a real random forest
oob_score=True, then oob_score_the out-of-bag R²
forest.score(X_test, y_test)the test R²
r2_score, mean_absolute_error, root_mean_squared_errorthe measures of regression
forest.estimators_the list of the trees
BaggingRegressor(estimator=..., n_estimators=100)bagging around any regression model
df.drop_duplicates()drop the repeated rows, before the split
X_train.fillna(medians)fill with the training medians, after the split

Rules to keep

  1. A regression tree chooses the split with the lowest weighted squared error; its leaves predict means.
  2. A regression forest predicts the mean of its trees, and never leaves the range of the training values.
  3. The default RandomForestRegressor is bagging of trees; tune max_features with the OOB R² or cross-validation.
  4. Judge regression models with R², MAE and RMSE on the test data; the OOB R² chooses the hyperparameters.
  5. Drop repeated rows before the split, remove impossible values, and fill the missing values with the training medians after it.
  6. Bagging works around any model and cures variance: it helps deep trees a lot and linear regression not at all.
  7. No scaling for forests and bagged trees; the model inside a bagging decides its own preprocessing.

What comes next

Random forests and bagging train their trees independently and average them. Topic 32 brings a model that works in a completely different way: k-nearest neighbours, which predicts a class from the most similar rows; Topic 33 uses it for numbers. It needs distances, so scaling becomes essential again. Topic 34 is Naive Bayes, which calculates probabilities with Bayes' rule (Topic 16). Later, Topics 37 to 40 train trees one after another, each correcting the errors of the ones before: boosting.