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.
Lesson notebook
The lesson as a Jupyter notebook: the car project cell by cell, from the raw file through every preprocessing step to the random forest, bagging and the scores of every model, and the sixteen solved problems.
topic-31-random-forests-and-bagging-regression.ipynb, 89 KB
Practice notebook
The same project on the car adverts in twelve steps, from reading the raw file to a forest, bagged models and their scores, with a hint and a hidden solution for each step.
topic-31-practice.ipynb, 19 KB
Data file: the car adverts
10,000 adverts of cars for sale in Azerbaijan with 19 columns, drawn at random from a larger file and translated into English, without any data about the sellers. Not cleaned: repeated adverts, missing values and impossible values are still in it. The data of the lesson, the solved problems and the practice. From a public data set of car adverts (Kaggle).
car_prices.csv, 965 KB
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_featuresofRandomForestRegressor, 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.What stays the same and what changes when a forest predicts a number
- 2.How a regression tree chooses its questions with the squared error, and why its leaves predict a mean
- 3.How a regression forest predicts: the mean of the predictions of its trees
- 4.Why a forest cannot predict outside the range of the training prices
- 5.The hyperparameters of
RandomForestRegressor, and why its defaultmax_featuresmatters - 6.The measures R², MAE and RMSE, and the out-of-bag R²
- 7.What repeated rows, impossible values, missing values and many categories mean for the model
- 8.Bagging around any regression model with
BaggingRegressor: around trees and around linear regression - 9.A whole project: from the file to a tuned forest, bagged models, and the scores of all of them
| Word | Meaning |
|---|---|
| Regression forest | a random forest whose target is a number; it predicts the mean of its trees |
| Regression tree | a decision tree whose leaves predict a number: the mean of the training rows in the leaf |
| Squared error of a node | the 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 |
| MAE | mean absolute error: the typical error, in the unit of the target (manats) |
| RMSE | root 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 |
| Extrapolation | predicting outside the range of the training data; a forest cannot do it |
BaggingRegressor | bagging 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:
| Idea | In short | Where in Topic 30 |
|---|---|---|
| Bootstrap sample | every tree gets as many rows as the training data, drawn with replacement | Part 2, Step 1 |
| Out-of-bag rows | about 37 percent of the rows are not in a tree's sample | Part 2, Step 1 |
| Random features | at every split a tree chooses among a few random features (max_features) | Part 2, Step 2 |
| Deep trees | the trees are grown without limits by default; the averaging takes care of their variance | Part 2, Step 2 |
| Why many trees help | different trees make different mistakes, and the mistakes cancel in the average | Part 2 |
| Variance of an average | : more trees shrink the second part, less correlated trees the first | Part 2 |
| More trees never overfit | they only make the average more stable, and cost time | Part 4 |
| Bagging | the same model on many bootstrap samples, the answers combined; it works around any model | Part 9 |
| Bagging cures variance | it helps unstable models (deep trees) and hardly changes stable ones | Part 9 |
| Extremely randomized trees | random thresholds as well as random features | Part 9 |
If one of these is not clear, read its place in Topic 30 first: this lesson uses all of them.
1.2What changes
| Classification (Topic 30) | Regression (this topic) | |
|---|---|---|
| Target | a class: leaves (1) or stays (0) | a number: the price of a car in manats (AZN) |
| A tree chooses its split by | the Gini impurity or the entropy | the squared error |
| A leaf predicts | the share of each class in the leaf | the mean of the target in the leaf |
| The forest predicts | the mean of the trees' probabilities | the mean of the trees' predictions |
| Measures | accuracy, precision, recall, F1, AUC (Topic 28) | R², MAE, RMSE (Topic 22) |
Default max_features | "sqrt": the square root of the number of features | 1.0: all features |
oob_score_ holds | the out-of-bag accuracy | the out-of-bag R² |
class_weight | for unbalanced classes | does not exist: there are no classes |
| In scikit-learn | RandomForestClassifier, BaggingClassifier | RandomForestRegressor, 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
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
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.
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:
2.2An example with six cars
Six cars, their years and their prices in thousands of manats:
| Car | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| Year | 2008 | 2011 | 2014 | 2017 | 2019 | 2022 |
| Price (thousand AZN) | 8 | 10 | 12 | 24 | 28 | 32 |
Before any split, the node holds all six cars:
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:
The threshold 2012.5 puts only A and B on the left:
All five thresholds:
| Threshold | Left | Right | Error after the split |
|---|---|---|---|
| year ≤ 2009.5 | A | B, C, D, E, F | 63.467 |
| year ≤ 2012.5 | A, B | C, D, E, F | 37.667 |
| year ≤ 2015.5 | A, B, C | D, E, F | 6.667 |
| year ≤ 2018 | A, B, C, D | E, F | 27.167 |
| year ≤ 2020.5 | A, B, C, D, E | F | 53.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.)
- a car
- a leaf: the mean of its cars
- the threshold
Choose the threshold of the question "year ≤ ...?" for the six cars, and compare the squared error after the split.
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:
| criterion | The node's error | The leaf predicts |
|---|---|---|
"squared_error" (default) | the mean squared distance from the mean | the mean |
"absolute_error" | the mean absolute distance from the median | the 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
Show a hint
Show the solution
Answer: (a) 59.2; (b) 5.2; (c) 23 thousand AZN.
The split lowers the error from 59.2 to 5.2. The left leaf predicts the mean 8, the right leaf the mean .
3How a regression forest predicts
3.1Three steps
The forest is built exactly as in Topic 30; only the last step differs.
- Every tree gets its own bootstrap sample of the training cars.
- Every tree is grown with the squared error, choosing at each split among
max_featuresfeatures. - For a new car, every tree gives a price, and the forest predicts their mean.
Three trees and one car:
| Tree | Its prediction |
|---|---|
| Tree 1 | 18,500 AZN |
| Tree 2 | 21,000 AZN |
| Tree 3 | 22,600 AZN |
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:
With 100 trees the second part is tiny; the first part, the correlation of the trees, is what is left, and only more different trees make it smaller. Part 8 measures on the cars.
- ρ = 0
- ρ = 0.3
- ρ = 0.6
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.
- one tree (max_depth=3)
- forest of 100 such trees
- linear regression
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
Show a hint
Show the solution
Answer: (a) 13,700 AZN; (b) no; (c) linear regression.
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:
| Hyperparameter | Default | Role in a regression forest |
|---|---|---|
n_estimators | 100 | the 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_features | 1.0 | the 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_depth | None | the depth of every tree; the default grows full trees |
min_samples_split | 2 | the smallest node that may still be split |
min_samples_leaf | 1 | the smallest leaf: its prediction is the mean of at least this many cars |
bootstrap | True | every tree gets a bootstrap sample |
max_samples | None | the size of each bootstrap sample; None: as many rows as the training data |
oob_score | False | with True the forest computes its R² on the out-of-bag rows: oob_score_ |
n_jobs | None | how many processor cores train the trees at the same time; -1 uses all of them |
random_state | None | the 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_leafandmax_depthare 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_leafandmax_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
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
Show the solution
Answer: (a) 40; (b) 10; (c) no; (d) oob_score=True.
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 cars, true prices , predicted prices and the mean price :
Four cars, prices in thousands of manats:
| Car | True price | Predicted | Error |
|---|---|---|---|
| 1 | 20 | 22 | |
| 2 | 15 | 14 | 1 |
| 3 | 30 | 27 | 3 |
| 4 | 25 | 25 | 0 |
| Measure | Unit | What it says | When to look at it |
|---|---|---|---|
| MAE | manats | the typical error of a prediction | to tell a buyer how far off the price usually is |
| RMSE | manats | like the MAE, but large errors count much more; always at least the MAE | when a few large mistakes are costly |
| R² | none | the share of the variance of the prices that the model explains | to 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).
| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |
|---|---|---|---|---|
| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |
| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |
| Decision tree (29) | not needed | needed | robust | fill (recent scikit-learn can handle them) |
| Random forest, bagged trees (30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |
| Bagging around another model (30, 31) | as the model inside | as the model inside | as the model inside | as the model inside |
| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive | fill |
| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |
| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost, LightGBM and CatBoost handle them |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |
Try it yourself
Show a hint
Show the solution
Answer: (a) 1; (b) 1.291; (c) 0.931; (d) no.
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.
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
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:
| Column | Meaning |
|---|---|
brand, model | the make and the model of the car |
year | the year it was made |
engine_l, horsepower | the engine volume in litres and the power in horsepower |
fuel, gearbox, drive, body, colour | the kind of fuel, the gearbox, the driven wheels, the body type, the colour |
mileage_km | the kilometres driven |
seats, owners | the number of seats and of previous owners |
is_new, damaged, painted | 1 for a new car, for a car with accident damage, for a car with repainted parts |
market | the market the car was first sold in (official dealer, Europe, America, Korea, ...) |
city | where the car is sold |
price_azn | the price in manats (AZN): the target |
6.2Step 2: check
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
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
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:
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
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
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
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.
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()
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:
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
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
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
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
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
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
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
print(df["horsepower"].isna().sum())
print(round(df["market"].isna().mean(), 4))Output
3281 0.3095
7The random forest
7.1Train and judge
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
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
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
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:
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.
- one tree
- the mean: the forest
- the true price
7.6True against predicted prices
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()
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
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
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.
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()
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
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
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 trees can be computed from the trees we already have, without training new forests. First, the predictions of every tree for every test car:
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.
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 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.
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.
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()
8.2The out-of-bag R²: a free validation
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:
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
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
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:
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 table of the correlations of every pair of trees; without the 100 ones on its diagonal, 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
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
print(round(r2_score(y_test, tree_predictions[50:].mean(axis=0)), 4))Output
0.8653
Try it yourself
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
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:
| Hyperparameter | Default | Role |
|---|---|---|
estimator | a decision tree | the model inside, trained on every sample |
n_estimators | 10 | how many models (and bootstrap samples) |
max_samples | 1.0 | the size of each sample, as a share or a number of rows |
max_features | 1.0 | the share of the features each model gets (one random set per model, not per split) |
bootstrap | True | draw the rows with replacement |
oob_score | False | the out-of-bag R² |
random_state | None | the seed for the samples |
9.2Bagging around a full decision tree
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
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:
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.
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
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
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.
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()
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
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
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
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 10,000 adverts, 19 columns |
| 2. Check | missing values, repeated rows | four columns with gaps, 691 repeated rows |
| 3. Repeated rows | drop them before the split | 9,309 rows left |
| 4. Impossible values | find them with describe() | year 0, three million kilometres; engine 0 is right for electric cars |
| 5. Remove | the rows with impossible values | 9,259 rows left |
| 6. Too many categories | drop or group | model (816 values) dropped |
| 7. Target | its distribution and its outliers | real expensive cars, kept |
| 8. Rare categories | group them | brands with fewer than 50 cars become "other" |
| 9. Missing text | a category of its own | market: "unknown" |
| 10. Encode | text to numbers | one-hot: 83 features |
| 11. Split | training and test data | 7,407 and 1,852 |
| 12. Missing numbers | fill with the training medians, after the split | horsepower, seats, owners |
| 13. Scale | only for the models that need it | not for the forest, not for plain linear regression |
| 14. Model | the random forest | default: test R² 0.865 |
| 15. Look inside | trees, one car, importances, the range of the predictions | year and engine lead; no prediction above the training prices |
| 16. Tune | n_estimators, max_features and min_samples_leaf with the OOB R² | max_features=0.33 |
| 17. Model again | bagging around other models | trees gain, linear regression does not |
| 18. Judge | R², MAE and RMSE of every model on the same test data | the tuned forest and the extremely randomized trees lead |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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.
For the threshold 90:
For the threshold 40:
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).
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 are , and .
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).
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).
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).
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).
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 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).
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).
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².
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).
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).
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).
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).
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).
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).
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.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.
The leaves predict their means, 10 and 27.
- 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.
- 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 , , and ; the mean of the true prices is 16.Show one possible solution
Answer: MAE 1; RMSE 1.225; R² 0.925.
- 4.(a) A data set has 60 features. How many features does each split of
RandomForestRegressortry by default, and withmax_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.
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.
- 5.Read
car_prices.csvintodf. Print the shape, then the number of repeated rows.Show a hint
df = pd.read_csv("car_prices.csv"), thenprint(df.shape)andprint(df.duplicated().sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("car_prices.csv") print(df.shape) print(df.duplicated().sum())Output
(10000, 19) 691
- 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(), thendf = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)], thenprint(len(df)).Show one possible solution
Python, continues from the cells abovedf = df.drop_duplicates() df = df[(df["year"] >= 1950) & (df["mileage_km"] <= 1_000_000)] print(len(df))Output
9259
- 7.Drop the column
model, group the brands with fewer than 50 cars as"other", and fill the missingmarketwith"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"; thenprint((df["brand"] == "other").sum()).Show one possible solution
Python, continues from the cells abovedf = 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
- 8.One-hot encode the eight text columns of
text_columnswithdrop_first=Trueanddtype=int. Print the number of columns.Show a hint
df = pd.get_dummies(df, columns=text_columns, drop_first=True, dtype=int), thenprint(len(df.columns)).Show one possible solution
Python, continues from the cells abovetext_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.
- 9.Make
X(all columns withoutprice_azn) andy. Split them withtest_size=0.3andrandom_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), thenlen(y_test)andround(y_test.mean(), 1).Show one possible solution
Python, continues from the cells abovefrom 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
- 10.Fill
horsepower,seatsandownersinX_trainandX_testwith the medians of the training data. Print the median ofhorsepower, then the number of missing values left inX_test.Show a hint
medians = X_train[["horsepower", "seats", "owners"]].median(), thenX_train = X_train.fillna(medians)and the same forX_test;medians["horsepower"]andX_test.isna().sum().sum().Show one possible solution
Python, continues from the cells abovemedians = 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
- 11.Train a
RandomForestRegressorcalledforestwithrandom_state=42. Print its test R², rounded to 4 decimals.Show a hint
forest = RandomForestRegressor(random_state=42),forest.fit(X_train, y_train), thenforest.score(X_test, y_test).Show one possible solution
Python, continues from the cells abovefrom 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
- 12.Put the predictions of
forestfor the test cars intopredicted. Print the MAE and the RMSE as whole numbers.Show a hint
predicted = forest.predict(X_test), thenround(mean_absolute_error(y_test, predicted))and the same withroot_mean_squared_error.Show one possible solution
Python, continues from the cells abovefrom 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.
- 13.Train a forest with
max_features=0.5,oob_score=Trueandrandom_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, thenmodel.oob_score_.Show one possible solution
Python, continues from the cells aboveoob_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
- 14.Train a forest called
tunedwithmax_features=0.5andrandom_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 abovetuned = 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
- 15.Train a
BaggingRegressorof 100 full decision trees withrandom_state=42, calledbagged_trees. Print its test R², rounded to 4 decimals.Show a hint
bagged_trees = BaggingRegressor(estimator=DecisionTreeRegressor(), n_estimators=100, random_state=42),fit, thenscore.Show one possible solution
Python, continues from the cells abovefrom 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
- 16.Train a
BaggingRegressorof 100 linear regressions withrandom_state=42and print its test R², rounded to 4 decimals. Then draw the test R² offorest,tuned,bagged_treesand the bagged linear regression as horizontal bars.Show a hint
BaggingRegressor(estimator=LinearRegression(), n_estimators=100, random_state=42)onX_train(no scaling needed); a list of four names, a list of four scores,plt.barh(names, r2s)andplt.show().Show one possible solution
Python, continues from the cells aboveimport 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

14Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
15Summary
| Formula or rule | Meaning | |
|---|---|---|
| Squared error of a node | mean of | how far the values of a node lie from their mean |
| Error after a split | the tree takes the split with the smallest value | |
| A leaf predicts | the mean of its training values | never outside the training range |
| The forest predicts | the mean of the trees' predictions | no vote, no threshold |
| MAE | mean of | the typical error, in manats |
| RMSE | large errors count more; at least the MAE | |
| R² | the share of the variance explained | |
Default max_features | 1.0 for regression | the default regression forest is bagging of trees |
| Code | What it does |
|---|---|
RandomForestRegressor(random_state=42) | a forest of 100 full regression trees |
max_features=0.33 | a 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_error | the 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
- A regression tree chooses the split with the lowest weighted squared error; its leaves predict means.
- A regression forest predicts the mean of its trees, and never leaves the range of the training values.
- The default
RandomForestRegressoris bagging of trees; tunemax_featureswith the OOB R² or cross-validation. - Judge regression models with R², MAE and RMSE on the test data; the OOB R² chooses the hyperparameters.
- Drop repeated rows before the split, remove impossible values, and fill the missing values with the training medians after it.
- Bagging works around any model and cures variance: it helps deep trees a lot and linear regression not at all.
- 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.