Asiman Data School

Module 3, topic 30, week 15, Thursday

Random Forests and ensemble learning (bagging) - Classification

Many trees instead of one: bootstrap samples, random features and averaged probabilities, why this lowers the variance, the out-of-bag score, two kinds of feature importance, the hyperparameters, and bagging around trees and logistic regression, on the bank data from the file to the scores of every model.

Introduction: many trees instead of one

The tenth lesson of Module 3. Topic 29 ended with the weakness of a single decision tree: it is unstable. A few different training rows can change its first question and everything below it, and a tree without limits learns the training data by heart. This lesson turns that weakness into a strength. Instead of one tree, we train many trees, each on a slightly different version of the data, and let them decide together. This is a random forest, one of the most used models for tables of data.

The idea behind it has a name of its own: ensemble learning, combining many models into one. The random forest uses the simplest form of it, bagging, and the second half of the lesson shows that bagging is not only for trees: it can be put around any model.

The lesson has three steps. On paper: what a random forest is and where it is used, how it builds its trees (bootstrap samples and random features), how it chooses the questions inside each tree, how it decides, and its hyperparameters. Then the project on Bank Customer Churn Prediction.csv, the file of Topics 27 to 29: 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 logistic regression, and the scores of all models are compared.

You need: decision trees, the Gini impurity and the hyperparameters of a tree (Topic 29), logistic regression (Topic 27), the measures of Topic 28, cross-validation (Topic 23), scaling and encoding (Topics 24 and 25), and a little probability (Topic 16).

What you will learn

  1. 1.What a random forest is, and where it is used
  2. 2.What an ensemble is, and why many models can be better than one
  3. 3.How a random forest builds its trees: bootstrap samples and random features
  4. 4.How the trees choose their questions, and how the forest makes its decision
  5. 5.The out-of-bag score, and two kinds of feature importance
  6. 6.The hyperparameters of RandomForestClassifier and their roles
  7. 7.What scaling, encoding, outliers and missing values mean for forests, and for the models still to come
  8. 8.Bagging around any model with BaggingClassifier: around trees and around logistic 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
Ensemblea model made of several models whose answers are combined
Random forestan ensemble of decision trees, each trained on a bootstrap sample and with random features at each split
Bootstrap samplea sample of the same size as the training data, drawn with replacement: some rows appear twice or more, some not at all
Out-of-bag (OOB) rowsthe training rows that a bootstrap sample did not draw
Baggingbootstrap aggregating: train the same model on many bootstrap samples and combine the answers
Majority votethe class that most models predict
Averaging probabilitiesthe mean of the probabilities of all models; scikit-learn's forest decides this way
max_featureshow many features each split may choose from
OOB scorethe accuracy of the forest on its out-of-bag rows: a free validation score
Permutation importancehow much the score drops when one feature is shuffled

1What a random forest is

1.1Many trees instead of one

Ask one person to guess the weight of an ox, and the guess may be far off. Ask 800 people and take the mean of their guesses, and the mean is often closer than almost every single guess. This is the "wisdom of the crowd", observed at a country fair more than a hundred years ago. It works when the people make different mistakes: some guess too high, some too low, and the errors cancel out.

A random forest uses the same idea with decision trees:

  • It trains many trees, typically 100 or more.
  • Each tree sees a slightly different version of the training data and of the features, so the trees make different mistakes.
  • For a new customer every tree gives its answer, and the forest combines them.

One deep tree overfits: it has low bias and very high variance (Topic 23). Averaging many such trees keeps the low bias and lowers the variance. That is the whole trick.

1.2Ensembles

A model that combines several models is an ensemble. There are several families:

Ensembles
FamilyHow the models are madeHow they are combinedTopic
Baggingthe same model on many bootstrap samples, in parallelvote or averagethis topic
Random forestbagging of trees, plus random features at every splitaverage of the probabilitiesthis topic
Boostingmodels trained one after another, each one correcting the mistakes of the ones beforea weighted sumTopics 37 to 40
Votinga few different models (a tree, a logistic regression, ...)vote or averageTopics 35 and 36

This lesson is about the first two.

1.3Where random forests are used

  • Banking and insurance: churn (the project of this lesson), credit risk, fraud detection.
  • Medicine: predicting a disease from many measurements, finding which measurements matter most.
  • Business: which customers will buy, how many products will be sold.
  • Science: classifying land from satellite images, finding genes linked to a disease.
  • As a strong first model: for a table of data, a random forest with its default settings is often a good model before any tuning. Many practitioners train it first, to see what is possible.

1.4Strengths and weaknesses

Strengths and weaknesses
StrengthsWeaknesses
Usually much more accurate than one treeNo longer readable as a few rules: 100 trees
Overfits far less than one deep treeSlower to train and to predict than one tree, and bigger in memory
Works well with default settingsIts feature importances can mislead (Part 7 shows how)
No scaling needed, robust to outliersLike every tree, it cannot predict beyond the values of the training data (regression)
A free validation score: the OOB scoreOn some data, boosting (Topics 37 to 40) is more accurate

Try it yourself

(a) What is a model called that combines the answers of several models? (b) Which family trains the same model on many bootstrap samples, in parallel? (c) Which family trains models one after another, each correcting the ones before? (d) What does averaging many deep trees lower: the bias or the variance?

Show a hint
Look at the table of the ensemble families, and at "Many trees instead of one".
Show the solution

Answer: (a) an ensemble; (b) bagging; (c) boosting; (d) the variance.

A deep tree has a low bias and a high variance; the average of many different deep trees keeps the low bias and loses most of the variance.

2How a random forest works

A random forest is built in three steps.

training data8,000 customerssample 1sample 2sample 100tree 1random featurestree 2random featurestree 100random featuresthe forestmean of the probabilities
The three steps of a random forest. Step 1: every tree gets its own bootstrap sample of the training data. Step 2: a tree is grown on each sample, with a few random features at every split. Step 3: for a new customer the forest takes the mean of the probabilities of all trees.

2.1Step 1: a bootstrap sample for every tree

Each tree gets its own bootstrap sample: as many rows as the training data has, drawn with replacement. Drawing with replacement means: a row is drawn, written down, and put back, so it can be drawn again.

Take the ten customers A to J of Topic 29. One bootstrap sample of size 10 might be:

Step 1: a bootstrap sample for every tree
Draw12345678910
CustomerCAFCJFDIFH
  • C appears twice and F three times.
  • B, E and G were not drawn at all. They are the out-of-bag rows of this tree.

How many rows are left out? In one draw a given customer is missed with the probability 9 out of 10. In ten independent draws:

probability of being left out=0.910=0.349\begin{aligned} & \text{probability of being left out} \\[4pt] &= 0.9^{10} = 0.349 \end{aligned}

For large data the share approaches 1e=0.368\frac{1}{e} = 0.368. So every tree is trained on about 63 percent of the different rows, some of them several times, and about 37 percent of the rows are out of bag for it. Every tree sees a different mix, and every tree becomes a little different.

Draw a bootstrap sample of the ten customers: ten draws with replacement. Then draw again.

A2×B1×C1×DoutE1×F1×G2×H1×IoutJ1×

Sample 1: A, B, H, E, F, C, A, G, G, J. Out of bag: D, I.

Over 1 sample on average 20 percent of the customers were left out. Expected: 0.910 = 34.9 percent.

Every sample has ten rows, but some customers appear twice or more, so others are missing.

2.2Step 2: a tree with random features at every split

Each tree is grown as in Topic 29, with one change. At every split the tree does not try all features. It draws a few features at random and chooses the best question among them only. In scikit-learn the default for classification is the square root of the number of features:

features tried at a split=11=3.317, rounded down: 3\begin{aligned} & \text{features tried at a split} \\[4pt] &= \sqrt{11} = 3.317, \ \text{rounded down: } 3 \end{aligned}

So at each node of each tree, 3 of the 11 bank features are drawn, and the best question is chosen among those 3.

Why throw information away? Because otherwise all trees would look alike. In the bank data the age is the strongest feature (Topic 29): if every tree could choose it, every tree would start with the age, and 100 similar trees make the same mistakes. Hiding the strongest feature from some splits forces the trees to try other questions. The trees become less correlated, and the average of trees that disagree removes more of the variance.

By default the trees of a random forest are grown without limits: deep, overfitted trees. That is intended. Each tree has a low bias and a high variance, and the averaging takes care of the variance.

2.3Step 3: the decision

For a new customer every tree gives its answer. scikit-learn's forest takes the mean of the probabilities of all trees, and predicts the class with the larger mean.

Three trees and one customer:

Step 3: the decision
TreeProbability of leavingIts own class
Tree 10.8leaves
Tree 20.3stays
Tree 30.6leaves
probability of the forest=0.8+0.3+0.63=1.73=0.567\begin{aligned} & \text{probability of the forest} \\[4pt] &= \frac{0.8 + 0.3 + 0.6}{3} = \frac{1.7}{3} = 0.567 \end{aligned}

0.567 is above 0.5: the forest predicts "leaves". A majority vote gives the same answer here: two of the three trees say "leaves". The two ways usually agree, but not always; scikit-learn uses the mean of the probabilities. When the trees are grown to pure leaves, every tree gives 0 or 1, and the mean of the probabilities is simply the share of the trees that vote "leaves". A forest of 100 deep trees in which 4 trees say "leaves" gives the probability 0.04.

For a regression forest the answer is the mean of the predictions of the trees.

2.4Why many trees are better than one

Suppose each tree is right for 70 percent of the customers, and the trees make their mistakes independently of each other. Three trees decide by majority. The majority is right when all three are right, or when exactly two are right:

all three right:0.73=0.343exactly two right:3×0.72×0.3=3×0.49×0.3=0.441majority right:0.343+0.441=0.784\begin{aligned} \text{all three right:}\quad & 0.7^3 = 0.343 \\[6pt] \text{exactly two right:}\quad & 3 \times 0.7^2 \times 0.3 \\[4pt] & = 3 \times 0.49 \times 0.3 = 0.441 \\[6pt] \text{majority right:}\quad & 0.343 + 0.441 = 0.784 \end{aligned}

Three trees of 70 percent together reach 78.4 percent. With five trees:

0.75+5×0.74×0.3+10×0.73×0.32=0.168+0.360+0.309=0.837\begin{aligned} & 0.7^5 + 5 \times 0.7^4 \times 0.3 \\[4pt] & \quad + 10 \times 0.7^3 \times 0.3^2 \\[4pt] &= 0.168 + 0.360 + 0.309 = 0.837 \end{aligned}
0.50.75111121314151
  • each tree right with 0.7
  • each tree right with 0.6
The majority of independent trees. If each tree is right with the probability 0.7, the majority of 3 trees is right 0.784, of 5 trees 0.837, of 51 trees almost always. With 0.6 the climb is slower. Real trees are not independent, so their gain is smaller.

The more independent trees, the closer the majority comes to always being right. Real trees are not independent: they learn from the same data and make some of the same mistakes. That is why the forest does everything it can to make them different (bootstrap samples, random features), and why its gain is real but smaller than this picture.

Set how often each tree is right and how many independent trees vote.

The majority of 3 independent trees, each right with 0.7, is right with the probability 0.784.

Set p below 0.5: the majority is wrong more often than one tree. A crowd helps only when each member is better than guessing.

2.5Why averaging lowers the variance

The picture above assumed independent trees. A formula from statistics says what happens when they are not. Suppose every tree's prediction for a customer has the variance σ2\sigma^2 (how much it would change with another training sample), and every two trees are correlated with the correlation ρ\rho (Topic 20). The variance of the average of nn trees is:

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}

Take σ2=1\sigma^2 = 1 and 100 trees:

ρ=0:0+1100=0.01ρ=0.3:0.3+0.7100=0.307ρ=1:1+0100=1\begin{aligned} \rho = 0:\quad & 0 + \frac{1}{100} = 0.01 \\[6pt] \rho = 0.3:\quad & 0.3 + \frac{0.7}{100} = 0.307 \\[6pt] \rho = 1:\quad & 1 + \frac{0}{100} = 1 \end{aligned}

Three lessons are in this formula:

  • More trees shrink only the second part, (1−ρ) σ2n\frac{(1 - \rho)\,\sigma^2}{n}. With 100 trees it is already tiny, which is why the scores flatten after some hundred trees.
  • The first part, ρ×σ2\rho \times \sigma^2, does not shrink with more trees. Only less correlated trees make it smaller. This is the job of the bootstrap samples and, above all, of the random features.
  • If all trees were the same (ρ=1\rho = 1), a forest would be exactly as good as one tree.
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.

Part 9 measures the correlation of the trees on the bank data: about 0.3 for the random forest, more for plain bagged trees.

2.6Bias and variance of a forest

In the language of Topic 23:

  • Bias: a forest has about the bias of one deep tree, which is low. (A little higher, because each tree sees only a bootstrap sample and a few features at each split.)
  • Variance: much lower than that of one tree, by the formula above.

So a forest keeps what is good about deep trees (they can learn complicated patterns) and removes most of what is bad (they change with every training sample).

Try it yourself

(a) A bootstrap sample of the six customers A to F is A, D, A, F, C, A. Which customers are out of bag? (b) What is the probability that a given customer is left out of a bootstrap sample of size 6? Give 3 decimals; use (56)6=0.335\left(\tfrac{5}{6}\right)^6 = 0.335. (c) Four trees give the probabilities 0.7, 0.2, 0.6 and 0.3. What probability does the forest give?

Show a hint
Out of bag means never drawn. The forest takes the mean of the probabilities.
Show the solution

Answer: (a) B and E; (b) 0.335; (c) 0.45.

0.7+0.2+0.6+0.34=1.84=0.45\frac{0.7 + 0.2 + 0.6 + 0.3}{4} = \frac{1.8}{4} = 0.45

(a) B and E were never drawn; A was drawn three times. (c) 0.45 is below 0.5, so the forest predicts "stays", although two of the four trees would say "leaves".

3How the trees choose their questions

3.1The same scores as one tree

Inside a forest every tree is an ordinary decision tree (Topic 29). At each node it measures how mixed the classes are with the Gini impurity (the default, criterion="gini") or the entropy (criterion="entropy"), and takes the split with the lowest weighted impurity:

Gini=1−p2−(1−p)2\text{Gini} = 1 - p^2 - (1 - p)^2
impurity after the split=nleftn×impurityleft+nrightn×impurityright\begin{aligned} & \text{impurity after the split} \\[4pt] &= \frac{n_{\text{left}}}{n} \times \text{impurity}_{\text{left}} \\[4pt] &\quad + \frac{n_{\text{right}}}{n} \times \text{impurity}_{\text{right}} \end{aligned}

Only two things differ from a single tree: the rows of a tree are its bootstrap sample, and the candidates at each split are the few random features.

3.2An example with the ten customers

Topic 29 computed the Gini after each question for the ten customers:

An example with the ten customers
QuestionGini after the split
Over 50?0.317
Active member?0.40
Two or more products?0.45

A single tree tries all three and chooses "Over 50?". Now let each split of a forest see only 2 of the 3 questions:

  • A tree that draws "Over 50?" and "Two or more products?" chooses "Over 50?" (0.317 against 0.45).
  • A tree that draws "Over 50?" and "Active member?" also chooses "Over 50?".
  • A tree that draws "Active member?" and "Two or more products?" cannot see the age. It chooses "Active member?" (0.40 against 0.45) and grows a different tree.

The strongest question still wins most of the time, but not always. Over 100 trees this gives a variety of trees that all make sense.

3.3Feature importance in a forest

The feature importance of a forest is the importance of Topic 29 (how much a feature lowered the impurity), averaged over all trees. It is quick, because it comes from training. But it has a known weakness: features with many different values, such as a salary in euros, offer many thresholds, and deep trees use them to split off small groups of training rows, even when they say nothing about the target. Such features get too much importance.

A second measure checks this on the test data: the permutation importance. Shuffle one column of the test data, so that its values no longer belong to their customers, and measure how much the score falls. A feature the model really uses makes the score fall; a useless feature changes nothing. Part 7 compares the two on the bank data.

Try it yourself

The ten customers of Topic 29 give these Gini values after the split: "Over 50?" 0.317, "Active member?" 0.40, "Two or more products?" 0.45. At a split of a forest only two random questions are drawn. Which question is chosen (a) from "Active member?" and "Two or more products?", (b) from "Over 50?" and "Active member?"? (c) Which score do the trees of a forest use by default?

Show a hint
The lowest Gini after the split wins, among the questions that were drawn.
Show the solution

Answer: (a) Active member?; (b) Over 50?; (c) the Gini impurity.

Each tree is an ordinary decision tree; only the candidate questions are random. When the strongest question is not drawn, the tree takes the best of the others and grows differently.

4The hyperparameters of a random forest

RandomForestClassifier has the hyperparameters of a decision tree (Topic 29), which now apply to every tree, and a few of its own.

4.1The forest's own hyperparameters

The forest's own hyperparameters
HyperparameterDefaultRole
n_estimators100the number of trees. More trees: a more stable average, never more overfitting, but slower. The gain flattens after some hundred trees.
max_features"sqrt"how many features each split may choose from: "sqrt" (the square root of the number of features), "log2", a number, a share such as 0.5, or None (all features: then the forest is bagging of trees). Smaller: more different trees.
bootstrapTruewhether every tree gets a bootstrap sample. With False every tree sees all rows, and only the random features make the trees differ.
max_samplesNonethe size of each bootstrap sample (a number or a share). None: as many rows as the training data.
oob_scoreFalsewith True the forest scores itself on its out-of-bag rows: oob_score_.
n_jobsNonehow many processor cores train the trees at the same time; -1 uses all of them. The trees do not depend on each other, so they can be trained in parallel.
random_stateNonethe seed for all random choices (samples and features): the same forest at every run.
class_weightNone"balanced" gives the rare class more weight, as in Topics 27 and 29; "balanced_subsample" does the same inside each bootstrap sample.

4.2The hyperparameters of every tree

The hyperparameters of every tree
HyperparameterDefaultRole in a forest
criterion"gini"the impurity measure of every tree: "gini" or "entropy"
max_depthNonethe depth of every tree. The default grows full trees; a limit makes every tree simpler and the forest faster.
min_samples_split2the smallest node that may still be split
min_samples_leaf1the smallest leaf; larger leaves give smoother probabilities
max_leaf_nodesNonethe largest number of leaves of every tree
min_impurity_decrease0.0a split must lower the impurity at least this much
ccp_alpha0.0cost-complexity pruning of every tree

4.3Which ones matter most

  • n_estimators: more is better until the curve flattens; it is limited by time, not by overfitting. 100 to 500 is common.
  • max_features: the heart of the random forest. Smaller values make the trees more different; None turns the forest into bagging of trees.
  • max_depth and min_samples_leaf: the trees of a forest may overfit alone, but a limit can still help the forest a little, makes it faster, and smooths its probabilities.
  • class_weight: when the recall of the rare class matters (Topic 28).

They are chosen as before: with cross-validation on the training data (Topic 23), or with the OOB score. Searching several hyperparameters at once is the subject of Topic 42.

4.4Is a random forest safe from overfitting?

It is often said that a random forest "cannot overfit". That is half true:

  • Adding trees never makes it overfit. More trees only lower the second part of the variance formula. The test score with 1,000 trees is not worse than with 100; it only took longer.
  • The trees themselves can still learn noise. With full trees every leaf holds a single training row or a few, and the forest knows its training customers by heart: a training accuracy of 1.0 against 0.867 on the test data (Part 7). The gap is real overfitting. It is harmless as long as the test score is good, but it means that a forest must never be judged on its training data.
  • Its probabilities can be too sure. Deep trees give 0 or 1, and on noisy data the forest's probabilities become rough. Larger leaves (min_samples_leaf) or a limited depth (max_depth) smooth them, and on the bank data they raise the AUC (Part 8).

So a forest is robust: hard to spoil by its main setting, and good with the defaults. It is not immune: its trees are tuned with max_depth, min_samples_leaf and max_features, and it is judged on the OOB rows or the test data.

4.5Random forests for regression

Everything in this lesson also works for a number as the target, and Topic 31 is about it: RandomForestRegressor (and BaggingRegressor) average the predictions of their trees, and each tree chooses its questions by the squared error (Topic 29). The hyperparameters are the same; the default max_features of the regressor is 1.0 (all features).

Which hyperparameter is it?

1 of 8

More of it gives a steadier average and never more overfitting, only more time.

Try it yourself

(a) Does raising n_estimators from 100 to 500 make a forest overfit? (b) Which setting turns a forest into bagging of trees? (c) Which hyperparameter gives a free validation score? (d) Which hyperparameter makes the leaves of every tree larger?

Show a hint
Look at the two tables of hyperparameters.
Show the solution

Answer: (a) no; (b) max_features=None; (c) oob_score=True; (d) min_samples_leaf.

More trees only steady the average. With all features at every split only the bootstrap samples make the trees differ: bagging. The OOB score uses the rows each tree did not see. A larger min_samples_leaf makes every leaf keep more rows.

5Preprocessing for forests, and for the models still to come

Topic 29 explained why trees need less preprocessing than other models. A forest is made of trees, so the same holds:

  • Scaling: not needed. Every tree only asks whether a value is above a threshold.
  • Encoding: still needed. scikit-learn's forests accept only numbers. A number whose effect is not in order, such as products_number, can stay a number.
  • Outliers in the features: no harm, for the same reason as in a tree.
  • Missing values: recent versions of scikit-learn let forests work with them, as single trees can; in this course they are still looked at and filled on purpose (Topic 11).
  • Unbalanced classes: class_weight="balanced" or "balanced_subsample"; Topic 41 goes further.

Bagging is different: it can be put around any model, and then the model inside decides what preprocessing is needed. Bagging around logistic regression needs scaled features, because logistic regression needs them (Topic 27). Part 9 does exactly that.

Preprocessing for forests, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the features
Linear and logistic regression (22, 26, 27)neededneededsensitive
Decision tree (29)not neededneededrobust
Random forest, bagged trees (30, 31)not neededneededrobust
Bagging around another model (30, 31)as the model insideas the model insideas the model inside
k-nearest neighbours (32, 33)essential: distancesneededsensitive
Support vector machines, voting (35, 36)needed for the support vector machine; voting as the models insideneededsensitive
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robust
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitive

Topic 42 will put the preprocessing and the model into one object, so that the right steps always run in the right order.

Try it yourself

(a) Does a random forest need scaled features? (b) Must country be encoded for it? (c) Bagging is put around logistic regression. Must the data be scaled? (d) Do outliers in the features harm a forest?

Show a hint
A forest is made of trees. In a bagging, the model inside decides.
Show the solution

Answer: (a) no; (b) yes; (c) yes; (d) no.

The trees only compare values with thresholds, so scaling and outliers do not matter, but scikit-learn needs numbers. Bagging copies the model inside, with all its needs: logistic regression needs scaled features.

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

Now the data: Bank Customer Churn Prediction.csv, 10,000 customers of a bank, and the column churn says who left (1) and who stayed (0).

The data file: Bank Customer Churn Prediction.csv

10,000 customers, 12 columns. 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.

6.1Step 1: read and look

Python
import pandas as pd

df = pd.read_csv("Bank Customer Churn Prediction.csv")

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

Output

(10000, 12)
   customer_id  credit_score country  ... active_member  estimated_salary  churn
0     15634602           619  France  ...             1         101348.88      1
1     15647311           608   Spain  ...             1         112542.58      0
2     15619304           502  France  ...             0         113931.57      1
3     15701354           699  France  ...             0          93826.63      0
4     15737888           850   Spain  ...             1          79084.10      0

[5 rows x 12 columns]

10,000 rows and 12 columns: an identification number, ten features (credit score, country, gender, age, years as a customer, balance, number of products, credit card, active membership, estimated salary) and the target churn.

6.2Step 2: check

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

Output

0
0
customer_id           int64
credit_score          int64
country                 str
gender                  str
age                   int64
tenure                int64
balance             float64
products_number       int64
credit_card           int64
active_member         int64
estimated_salary    float64
churn                 int64
dtype: object

No missing values, no repeated rows. Two text columns: country and gender.

6.3Step 3: drop what carries no information

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

print(df.shape)

Output

(10000, 11)

An identification number says nothing about a customer. A forest of deep trees would even use it to separate single training customers: noise.

6.4Step 4: the target

Python, continues from the cells above
print(df["churn"].value_counts())
print(round(df["churn"].mean(), 4))

Output

churn
0    7963
1    2037
Name: count, dtype: int64
0.2037

About 20 percent of the customers left: the classes are unbalanced, and the measures of Topic 28 will judge the models.

6.5Step 5: outliers

Python, continues from the cells above
q1 = df["age"].quantile(0.25)
q3 = df["age"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)

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

Output

62.0
359

359 customers are older than the upper limit of the IQR rule (Topic 25). They are real customers, and the trees of a forest only compare the age with thresholds. They stay.

6.6Step 6: encode

Python, continues from the cells above
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)

print(df.columns.tolist())

Output

['credit_score', 'gender', 'age', 'tenure', 'balance', 'products_number', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain']

gender becomes 0 and 1, country gets one-hot encoding, and products_number stays a number: the trees split it where they need to (Topic 29).

6.7Step 7: split

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

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

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

(8000, 11) (2000, 11)

Change it and run: change test_size to 0.3 and run: 3,000 customers become test data.

8,000 customers for training and 2,000 for the test, the same customers as in Topics 27 to 29, so all results can be compared.

6.8Step 8: no scaling

A forest needs no scaling. The features stay as they are. (Part 9 will scale them for logistic regression, which needs it.)

7The random forest

7.1Train and judge

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

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

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

Output

1.0
0.867

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

RandomForestClassifier lives in sklearn.ensemble, the part of scikit-learn for ensembles. With its default settings (100 full trees) the forest is right for every training customer, like a single full tree, but on the test data it reaches 0.867: far above the full tree of Topic 29 (0.7845) and above the tuned tree (0.8575).

A training accuracy of 1.0 is no alarm for a forest: its trees are meant to be deep. What counts is the test score.

7.2Inside the forest

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

Output

100
[22, 26, 24, 21, 26]

estimators_ is the list of the 100 trained trees, each an ordinary DecisionTreeClassifier. The first five are between 21 and 26 levels deep: full trees, each different because of its bootstrap sample and its random features.

7.3How the forest decides for one customer

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

votes = [tree.predict(customer.values)[0] for tree in forest.estimators_]

print(sum(votes))
print(forest.predict_proba(customer))
print(forest.predict(customer))

Output

4.0
[[0.96 0.04]]
[0]

Change it and run: change iloc[[0]] to iloc[[5]] and count the votes for another customer.

The list votes holds the answer of each of the 100 trees for the first test customer (.values passes the plain numbers: the trees inside the forest were trained without the column names). 4 of the 100 trees say "leaves". Each full tree gives the probability 0 or 1, so the mean of the probabilities is 4 out of 100: predict_proba says 0.04, and the forest predicts 0, "stays".

7.4The measures of Topic 28

Python, continues from the cells above
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score

predicted = forest.predict(X_test)
leaving = forest.predict_proba(X_test)[:, 1]

print(confusion_matrix(y_test, predicted))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, leaving), 4))

Output

[[1549   58]
 [ 208  185]]
0.7613
0.4707
0.5818
0.856
The measures of Topic 28
MeasureFull tree (Topic 29)Tree with max_depth=5 (Topic 29)Random forest
Accuracy0.78450.85750.867
Precision0.45620.76470.7613
Recall0.50380.39690.4707
F1-score0.47880.52260.5818
AUC0.67850.83280.856

The forest wins on almost every measure. The full trees inside it overfit one by one, but their average does not: its AUC is 0.856 against 0.6785 for one full tree. Averaging 100 probabilities of 0 or 1 gives 101 possible probabilities, so the forest can rank the customers, which a single full tree could not.

7.5Feature importances

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

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

Output

age                 0.240
estimated_salary    0.146
credit_score        0.144
balance             0.138
products_number     0.131
tenure              0.082
active_member       0.041
country_Germany     0.026
gender              0.019
credit_card         0.019
country_Spain       0.013
dtype: float64

The age leads again. But the estimated salary and the credit score come next, before the number of products and the activity, which decided the tree of Topic 29. Is the salary really so important?

Python, continues from the cells above
from sklearn.inspection import permutation_importance

result = permutation_importance(forest, X_test, y_test, n_repeats=5, random_state=42)
permuted = pd.Series(result.importances_mean, index=X.columns)

print(permuted.sort_values(ascending=False).round(4))

Output

age                 0.0655
products_number     0.0583
active_member       0.0261
country_Germany     0.0144
balance             0.0115
credit_score        0.0051
tenure              0.0049
country_Spain       0.0029
credit_card         0.0028
gender              0.0018
estimated_salary   -0.0024
dtype: float64

Change it and run: change n_repeats=5 to n_repeats=10 and run: the order of the features stays the same.

permutation_importance shuffles each column of the test data 5 times (n_repeats=5) and reports how much the accuracy falls on average. The picture changes: the age, the number of products and the activity matter most, and the estimated salary is at the bottom with a value just below 0, which means shuffling it does not hurt at all. Its high impurity importance came from the many thresholds a column of euros offers: the deep trees used it to split off small groups of training customers.

Impurity importance

from training, averaged over the trees

Permutation importance

drop of the test accuracy when shuffled

The two importances of the bank forest. The impurity importance (left) puts the estimated salary and the credit score near the top. The permutation importance on the test data (right) shows what really matters: the age, the number of products and the activity; the salary is at the bottom.
Python, continues from the cells above
import matplotlib.pyplot as plt

permuted.sort_values().plot(kind="barh")
plt.title("Permutation importance of the forest on the test data")
plt.xlabel("drop of the accuracy when the column is shuffled")
plt.show()
Chart: Permutation importance of the forest on the test data

Rule: the impurity importance is a quick first look; to decide which features a forest really uses, check it with the permutation importance on the test data.

Try it yourself

This task continues from the cells above. Take the second test customer (position 1) as a table of one row. Print how many of the 100 trees say "leaves" for him, then predict_proba of the forest.
Show a hint
second = X_test.iloc[[1]], votes = [tree.predict(second.values)[0] for tree in forest.estimators_], then print(sum(votes)) and print(forest.predict_proba(second)).
Show the solution
Python, continues from the cells above
second = X_test.iloc[[1]]

votes = [tree.predict(second.values)[0] for tree in forest.estimators_]

print(sum(votes))
print(forest.predict_proba(second))

Output

8.0
[[0.92 0.08]]

8Tuning the forest

8.1n_estimators: how many trees?

Python, continues from the cells above
for n in [1, 5, 10, 50, 100, 200]:
    model = RandomForestClassifier(n_estimators=n, random_state=42)
    model.fit(X_train, y_train)
    leaving = model.predict_proba(X_test)[:, 1]
    print(n, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))

Output

1 0.78 0.6718
5 0.8335 0.7858
10 0.857 0.821
50 0.8615 0.8487
100 0.867 0.856
200 0.8665 0.8609

Every line shows the number of trees, the test accuracy and the test AUC.

  • One tree is about as good as the single full tree of Topic 29, a little worse even, because it saw only a bootstrap sample.
  • From 1 to 50 trees the scores rise steeply, then they flatten: 100 and 200 trees give almost the same.
  • More trees never make the forest overfit; they only cost time.

Choose the number of trees of a forest trained on the bank data, from 1 to 200.

0.650.750.85150100150200

100 trees: test accuracy 0.867, test AUC 0.856.

Orange: accuracy, teal: AUC. After about 50 trees the curves are flat: more trees cost time, not quality.

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

sizes = [1, 2, 5, 10, 20, 50, 100, 200]
aucs = []

for n in sizes:
    model = RandomForestClassifier(n_estimators=n, random_state=42)
    model.fit(X_train, y_train)
    aucs.append(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]))

plt.plot(sizes, aucs, marker="o")
plt.xscale("log")
plt.xlabel("n_estimators (number of trees)")
plt.ylabel("test AUC")
plt.title("More trees: a rising, then flat curve")
plt.show()
Chart: More trees: a rising, then flat curve

plt.xscale("log") spaces 1, 10 and 100 evenly on the horizontal axis, so that the small numbers of trees are not squeezed together.

8.2The out-of-bag score: a free validation

Every tree has its out-of-bag rows, about a third of the training data, which it never saw. With oob_score=True the forest predicts each training customer only with the trees for which he was out of bag, and reports the accuracy of these predictions:

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

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

Output

0.8574
0.867

Change it and run: add n_estimators=300 and run: the OOB score comes closer to the test score.

The OOB accuracy, 0.8574, is close to the test accuracy, 0.867, and it was measured without the test data and without cross-validation. It comes for free with bagging.

8.3max_depth, chosen with cross-validation

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

for depth in [8, 10, 12]:
    model = RandomForestClassifier(max_depth=depth, random_state=42)
    scores = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
    print(depth, round(scores.mean(), 4))

Output

8 0.8593
10 0.8606
12 0.8582

Every line shows the depth of every tree and the mean AUC of five folds on the training data. This cell trains 3×5=153 \times 5 = 15 forests of 100 trees each, so it takes a few seconds. A depth of 10 gives the highest mean AUC.

8.4min_samples_leaf and max_features

Python, continues from the cells above
for leaf in [1, 5, 10, 20]:
    model = RandomForestClassifier(min_samples_leaf=leaf, random_state=42)
    model.fit(X_train, y_train)
    leaving = model.predict_proba(X_test)[:, 1]
    print(leaf, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))

Output

1 0.867 0.856
5 0.863 0.8693
10 0.8595 0.8688
20 0.862 0.8681

Larger leaves lower the accuracy a little and raise the AUC: the probabilities become smoother, and the customers are ranked better.

Python, continues from the cells above
for features in ["sqrt", 0.5, None]:
    model = RandomForestClassifier(max_features=features, random_state=42)
    model.fit(X_train, y_train)
    leaving = model.predict_proba(X_test)[:, 1]
    print(features, round(model.score(X_test, y_test), 4), round(roc_auc_score(y_test, leaving), 4))

Output

sqrt 0.867 0.856
0.5 0.868 0.8574
None 0.857 0.8496

With max_features=None every split sees all 11 features: the forest becomes plain bagging of trees, and both scores fall. The random features make the difference between bagging and a random forest, and here they help.

8.5The tuned forest

Python, continues from the cells above
tuned = RandomForestClassifier(max_depth=10, random_state=42)
tuned.fit(X_train, y_train)

predicted = tuned.predict(X_test)
leaving = tuned.predict_proba(X_test)[:, 1]

print(confusion_matrix(y_test, predicted))
print(round(tuned.score(X_test, y_test), 4))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, leaving), 4))

Output

[[1553   54]
 [ 217  176]]
0.8645
0.7652
0.4478
0.565
0.871

Change it and run: change max_depth=10 to max_depth=8 and run.

The tuned forest has the highest AUC of the lesson, 0.871: of all models so far it ranks the customers best. Its accuracy and F1-score are close to those of the default forest.

8.6More recall: class_weight

Python, continues from the cells above
balanced = RandomForestClassifier(max_depth=10, class_weight="balanced", random_state=42)
balanced.fit(X_train, y_train)

predicted_balanced = balanced.predict(X_test)

print(round(recall_score(y_test, predicted_balanced), 4))
print(round(precision_score(y_test, predicted_balanced), 4))
print(round(f1_score(y_test, predicted_balanced), 4))

Output

0.6743
0.5942
0.6317

The recall rises from about 0.45 to 0.67, the precision falls, and the F1-score rises. For a bank that wants to find the customers who are about to leave (Topic 28), this is the more useful forest.

Try it yourself

This task continues from the cells above. Train a forest of 300 trees with random_state=42. Print its test accuracy and its test AUC, each rounded to 4 decimals. Did 300 trees overfit?
Show a hint
model = RandomForestClassifier(n_estimators=300, random_state=42), fit, then score and roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]). Compare with 100 and 200 trees.
Show the solution
Python, continues from the cells above
model = RandomForestClassifier(n_estimators=300, random_state=42)
model.fit(X_train, y_train)

print(round(model.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4))

Output

0.8665
0.8626

Try it yourself

This task continues from the cells above. Train a forest with max_depth=10, min_samples_leaf=5 and random_state=42. Print its test accuracy and its test AUC, each rounded to 4 decimals.
Show a hint
model = RandomForestClassifier(max_depth=10, min_samples_leaf=5, random_state=42), fit, then score and roc_auc_score.
Show the solution
Python, continues from the cells above
model = RandomForestClassifier(max_depth=10, min_samples_leaf=5, random_state=42)
model.fit(X_train, y_train)

print(round(model.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4))

Output

0.8625
0.8712

9Bagging: the idea behind the forest, for any model

9.1A random forest is bagging plus random features

Bagging (bootstrap aggregating) is the first two steps of Part 2 without the random features:

  1. Draw many bootstrap samples of the training data.
  2. Train the same kind of model on each sample.
  3. Combine the answers: the mean of the probabilities (or a majority vote) for a classifier, the mean of the predictions for a regression.

A random forest is bagging of decision trees, plus one extra: random features at every split. So:

random forest=bagging of decision trees+random features at every split\begin{aligned} & \text{random forest} \\[4pt] &= \text{bagging of decision trees} \\[4pt] &\quad + \text{random features at every split} \end{aligned}

Bagging helps a model that is unstable, a model with a high variance: one that changes a lot when the training data changes a little. A full decision tree is the perfect example. A stable model, one that gives almost the same answer on every bootstrap sample, gains little: averaging 100 almost equal models gives the same model again. Logistic regression is such a model.

In scikit-learn bagging is BaggingClassifier (and BaggingRegressor) from sklearn.ensemble. Its main hyperparameters:

A random forest is bagging plus random features
HyperparameterDefaultRole
estimatora decision treethe model inside, which is 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 accuracy, as in the forest
random_stateNonethe seed for the samples

9.2Why bootstrap samples, and not simply parts of the data?

Another way to get different training sets would be to cut the 8,000 training customers into 100 parts of 80. But a tree trained on 80 customers is a weak tree: its bias is high. A bootstrap sample has as many rows as the data, so every model is about as strong as one trained on all the data, and still a little different. That is the trick of the bootstrap: different samples without smaller samples.

(Drawing smaller samples without replacement also exists; it is called pasting, BaggingClassifier(bootstrap=False, max_samples=0.5). Bagging with the bootstrap is the common choice.)

The project continues on the same data.

9.3Bagging around a full decision tree

Python, continues from the cells above
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier

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

bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)
bagged_trees.fit(X_train, y_train)

print(round(full_tree.score(X_test, y_test), 4), round(bagged_trees.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, full_tree.predict_proba(X_test)[:, 1]), 4))
print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))

Output

0.7845 0.8585
0.6785
0.8507

estimator=DecisionTreeClassifier() is the model inside. One full tree: accuracy 0.7845 and AUC 0.6785. A hundred bagged full trees: accuracy 0.8585 and AUC 0.8507. Bagging alone repairs most of the overfitting. The random forest (0.867 and 0.856) adds a little more with its random features.

9.4Why the forest beats bagging: less correlated trees

The variance formula of Part 2 says that the forest gains over plain bagging by making its trees less correlated. This can be measured. Each tree of a forest (or of a bagging) gives a probability for every test customer; np.corrcoef gives the correlation of every pair of trees:

Python, continues from the cells above
import numpy as np

forest_probs = np.array([tree.predict_proba(X_test.values)[:, 1] for tree in forest.estimators_])
bagged_probs = np.array([tree.predict_proba(X_test.values)[:, 1] for tree in bagged_trees.estimators_])

print(forest_probs.shape)

Output

(100, 2000)

forest_probs is a table with one row for each of the 100 trees and one column for each of the 2,000 test customers.

Python, continues from the cells above
forest_corr = np.corrcoef(forest_probs)
bagged_corr = np.corrcoef(bagged_probs)

print(round((forest_corr.sum() - 100) / (100 * 99), 3))
print(round((bagged_corr.sum() - 100) / (100 * 99), 3))

Output

0.315
0.378

np.corrcoef gives a 100×100100 \times 100 table of the correlations of every pair of trees. Its diagonal holds the 100 correlations of a tree with itself, all 1; the rest are the 100×99100 \times 99 pairs, so sum−100100×99\frac{\text{sum} - 100}{100 \times 99} is their mean.

The trees of the random forest are correlated with about 0.315, the bagged trees with about 0.378. The random features made the trees less alike, and by the formula of Part 2 the average of less alike trees has a smaller variance. That is the difference between the two models in one number.

9.5Bagging around a shallow tree

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

bagged_shallow = BaggingClassifier(estimator=DecisionTreeClassifier(max_depth=5), 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))
print(round(roc_auc_score(y_test, shallow.predict_proba(X_test)[:, 1]), 4))
print(round(roc_auc_score(y_test, bagged_shallow.predict_proba(X_test)[:, 1]), 4))

Output

0.8575 0.865
0.8328
0.8578

Change it and run: change both max_depth=5 to max_depth=3 and run: the shallower tree gains even more from bagging.

The tuned tree of Topic 29 gains too: a little accuracy, and clearly more AUC, from 0.8328 to 0.8578. A tree of depth 5 is already more stable than a full tree, so the gain is smaller, but the averaged probabilities are much finer than the 32 probabilities of one tree.

9.6Bagging around logistic regression

Bagging works around any classifier. Logistic regression needs scaled features (Topic 27), so the data is scaled first, with the scaler fitted on the training data:

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

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

print(X_train_scaled.shape, X_test_scaled.shape)

Output

(8000, 11) (2000, 11)
Python, continues from the cells above
from sklearn.linear_model import LogisticRegression

logistic = LogisticRegression()
logistic.fit(X_train_scaled, y_train)

bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)
bagged_logistic.fit(X_train_scaled, y_train)

print(round(logistic.score(X_test_scaled, y_test), 4), round(bagged_logistic.score(X_test_scaled, y_test), 4))
print(round(roc_auc_score(y_test, logistic.predict_proba(X_test_scaled)[:, 1]), 4))
print(round(roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1]), 4))

Output

0.811 0.8115
0.7789
0.7787

The 100 bagged logistic regressions give almost exactly the scores of one logistic regression: 0.811 against 0.8115, and an AUC of 0.7789 against 0.7787. Each bootstrap sample gives nearly the same weights, so their average is the same model again. Bagging cures variance, and logistic regression has little of it. (This logistic regression uses the eleven features with products_number as a number, as the first model of Topic 27; its one-hot encoding would help it, not bagging.)

9.7A relative: extremely randomized trees

The random forest makes its trees different with bootstrap samples and random features. Extremely randomized trees go one step further: at each split they also draw the threshold at random for each candidate feature, instead of searching for the best one, and by default they train every tree on all rows, without a bootstrap. The trees become even more different, and faster to train.

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

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

print(round(extra.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, extra.predict_proba(X_test)[:, 1]), 4))

Output

0.8685
0.8518

On the bank data the extremely randomized trees are about as good as the random forest. It is one more model of the same family worth trying; it is used exactly as RandomForestClassifier, with the same hyperparameters.

9.8The scores of every model

Python, continues from the cells above
models = [
    ("full tree", full_tree, X_test),
    ("tree, max_depth=5", shallow, X_test),
    ("bagged full trees", bagged_trees, X_test),
    ("bagged trees, max_depth=5", bagged_shallow, X_test),
    ("random forest", forest, X_test),
    ("tuned random forest", tuned, X_test),
    ("logistic regression", logistic, X_test_scaled),
    ("bagged logistic regression", bagged_logistic, X_test_scaled),
]

for name, model, X_part in models:
    predicted = model.predict(X_part)
    leaving = model.predict_proba(X_part)[:, 1]
    print(name, round(f1_score(y_test, predicted), 4), round(roc_auc_score(y_test, leaving), 4))

Output

full tree 0.4788 0.6785
tree, max_depth=5 0.5226 0.8328
bagged full trees 0.5807 0.8507
bagged trees, max_depth=5 0.5545 0.8578
random forest 0.5818 0.856
tuned random forest 0.565 0.871
logistic regression 0.2948 0.7789
bagged logistic regression 0.2953 0.7787

Every line shows a model, its F1-score and its AUC on the same 2,000 test customers. The list holds, for each model, its name, the model and the test data it needs: the scaled data for logistic regression, the plain data for the trees.

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

names = [name for name, model, X_part in models]
aucs = [roc_auc_score(y_test, model.predict_proba(X_part)[:, 1]) for name, model, X_part in models]

plt.barh(names, aucs)
plt.xlim(0.6, 0.9)
plt.xlabel("test AUC")
plt.title("Single models, bagged models and random forests")
plt.show()
Chart: Single models, bagged models and random forests

What the comparison shows:

  • Bagging lifts the unstable full tree from the worst model to one of the best.
  • Bagging helps the shallow tree too, less strongly.
  • Bagging does nothing for the stable logistic regression.
  • The random forest, bagging plus random features, is the best of all, and the tuned forest leads.

Try it yourself

This task continues from the cells above. Train a BaggingClassifier of 100 full trees with oob_score=True and random_state=42. Print its OOB score, then its test accuracy, each rounded to 4 decimals.
Show a hint
model = BaggingClassifier(estimator=DecisionTreeClassifier(), 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
model = BaggingClassifier(estimator=DecisionTreeClassifier(), 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.8535
0.8585

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 customers, 12 columns
2. Checkmissing values, repeated rows, text columnsnothing missing; two text columns
3. Dropcolumns without informationcustomer_id
4. Targetthe share of each class20 percent left: unbalanced
5. Outliersfind them, decidereal customers, kept
6. Encodetext to numbersgender 0 and 1, country one-hot, products_number a number
7. Splittraining and test data8,000 and 2,000
8. Scaleonly for the models that need itnot for the forest; for logistic regression and its bagging
9. Modelthe random forestdefault: accuracy 0.867, AUC 0.856
10. Look insidetrees, votes, importancespermutation importance: age, products, activity
11. Tunen_estimators, max_depth (cross-validation), OOB scoremax_depth=10: AUC 0.871
12. Model againbagging around other modelstrees gain, logistic regression does not
13. Judgethe scores of every model on the same test datathe forest leads

Try it yourself

(a) For which models of this project were the features scaled? (b) What is the step "model again"? (c) On which data are all models compared? (d) Which model had the highest AUC?

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

Answer: (a) logistic regression and its bagging; (b) bagging around other models; (c) the same test data; (d) the tuned random forest.

Only logistic regression needs scaled features. After the forest the project trains bagged models, and all of them are judged on the same 2,000 test customers; the tuned forest ranks them best.

11Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Worrying about a training accuracy of 1.0 in a forest.Its trees are meant to be deep; the averaging handles the variance.Judge the forest on the test data or with the OOB score.
Thinking more trees cause overfitting.More trees only make the average more stable.Raise n_estimators until the scores flatten.
Thinking a random forest cannot overfit.Its full trees know the training rows by heart; only more trees are harmless.Judge on OOB or test data; tune max_depth and min_samples_leaf.
Scaling the features for a forest.It changes nothing.Scale only for models that need it.
Trusting the impurity importances alone.They favour features with many values, such as a salary.Check with permutation_importance on the test data.
Thinking max_features=None is "the best, it uses everything".It removes what makes a forest different from bagging.Keep "sqrt" or tune it.
Expecting bagging to improve every model.It cures variance; a stable model gains nothing.Bag unstable models, such as deep trees.
Bagging logistic regression on unscaled data.The model inside still needs its preprocessing.Scale first, as for one logistic regression.
Forgetting random_state.The bootstrap samples and the features change at every run.Fix random_state.
Confusing the bootstrap sample with a smaller sample.It has as many rows as the data; it is drawn with replacement.About 63 percent of the rows are in it, some several times.
Choosing max_depth with the test data.The test data then helps to build the model.Cross-validation or the OOB score.
Thinking a random forest can be read like one tree.It is 100 trees.Use importances to explain it, one tree at a time only for a look.

12Solved problems

The first four problems are short and solved by hand. Problems 5 to 16 are one project on Bank Customer Churn Prediction.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: A bootstrap sample

From the five customers A, B, C, D, E a bootstrap sample of size 5 is drawn: B, D, B, E, B. (a) Which customers are out of bag? (b) What is the probability that a given customer is left out of a bootstrap sample of size 5?

Idea. Drawing with replacement; a customer is missed in one draw with the probability 4 out of 5 (Part 2).

probability of being left out=0.85=0.328\text{probability of being left out} = 0.8^5 = 0.328

Why: A and C were not drawn: they are out of bag. B was drawn three times. About a third of the rows is left out of every bootstrap sample.

Problem 2: The decision of a forest

A forest of four trees gives a customer the probabilities of leaving 0.9, 0.4, 0.7 and 0.2. What does the forest predict?

Idea. scikit-learn's forest takes the mean of the probabilities (Part 2).

probability of the forest=0.9+0.4+0.7+0.24=2.24=0.55\begin{aligned} & \text{probability of the forest} \\[4pt] &= \frac{0.9 + 0.4 + 0.7 + 0.2}{4} = \frac{2.2}{4} = 0.55 \end{aligned}

Why: 0.55 is above 0.5: the forest predicts "leaves". A majority vote would have a tie here (two trees above 0.5, two below); the mean of the probabilities decides.

Problem 3: The majority of three

Three independent trees are each right with the probability 0.8. How often is their majority right?

Idea. The majority is right when all three or exactly two are right (Part 2).

all three right:0.83=0.512exactly two right:3×0.82×0.2=3×0.64×0.2=0.384majority right:0.512+0.384=0.896\begin{aligned} \text{all three right:}\quad & 0.8^3 = 0.512 \\[6pt] \text{exactly two right:}\quad & 3 \times 0.8^2 \times 0.2 \\[4pt] & = 3 \times 0.64 \times 0.2 = 0.384 \\[6pt] \text{majority right:}\quad & 0.512 + 0.384 = 0.896 \end{aligned}

Why: three trees of 80 percent make a majority of almost 90 percent, if their mistakes are independent. Random forests make their trees as different as they can for this reason.

Problem 4: Features at a split

A data set has 25 features. How many features does each split of a RandomForestClassifier try with the default max_features="sqrt"? And with max_features=None?

Idea. The square root of the number of features (Part 2).

25=5\sqrt{25} = 5

Why: 5 random features per split by default. With None every split tries all 25, and the forest becomes bagging of trees.

Problem 5: Read and check

Read the file. Print its shape, the number of missing values and the share of customers who left, rounded to 4 decimals.

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

Python
import pandas as pd

df = pd.read_csv("Bank Customer Churn Prediction.csv")

print(df.shape)
print(df.isna().sum().sum())
print(round(df["churn"].mean(), 4))

Output

(10000, 12)
0
0.2037

Why: nothing to fill, and one customer in five left.

Problem 6: Drop and encode

Drop customer_id, encode gender as 0 (Female) and 1 (Male), and one-hot encode country with drop_first=True. Print the number of columns.

Idea. Text to numbers; products_number stays a number for trees (Part 6).

Python, continues from the cells above
df = df.drop(columns=["customer_id"])
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)

print(len(df.columns))

Output

12

Why: eleven features and the target. No scaling follows: a forest does not need it.

Problem 7: Split

Make X and y and split them with test_size=0.25 and random_state=7. Print the shapes of X_train and X_test.

Idea. The split comes before any model learns from the rows.

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

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

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

(7500, 11) (2500, 11)

Why: 7,500 customers to learn from and 2,500 to judge with.

Problem 8: A random forest

Train a RandomForestClassifier with random_state=42. Print its training accuracy and its test accuracy, rounded to 4 decimals.

Idea. The default forest of Part 7.

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

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

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

Output

1.0
0.8604

Why: perfect on the training data, as its full trees are, and clearly better on the test data than a single tree.

Problem 9: Its measures

Print the confusion matrix, the recall, the F1-score and the AUC of the forest, the last three rounded to 4 decimals.

Idea. The measures of Topic 28; the AUC needs the probabilities.

Python, continues from the cells above
from sklearn.metrics import confusion_matrix, recall_score, f1_score, roc_auc_score

predicted = forest.predict(X_test)
leaving = forest.predict_proba(X_test)[:, 1]

print(confusion_matrix(y_test, predicted))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, leaving), 4))

Output

[[1912   78]
 [ 271  239]]
0.4686
0.578
0.8559

Why: the forest finds almost half of the leaving customers with few false alarms, and its AUC lies far above that of a single full tree.

Problem 10: The votes for one customer

Count how many of the forest's trees say "leaves" for the first test customer, and print predict_proba for him.

Idea. estimators_ holds the trees; full trees give 0 or 1, so the mean of the probabilities is the share of the votes (Part 7).

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

votes = [tree.predict(customer.values)[0] for tree in forest.estimators_]

print(sum(votes))
print(forest.predict_proba(customer))

Output

70.0
[[0.3 0.7]]

Why: the number of votes divided by 100 is the second number of predict_proba.

Problem 11: More trees

For 10, 50 and 100 trees, print the number of trees and the test AUC, rounded to 4 decimals.

Idea. n_estimators (Part 8).

Python, continues from the cells above
for n in [10, 50, 100]:
    model = RandomForestClassifier(n_estimators=n, random_state=42)
    model.fit(X_train, y_train)
    print(n, round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4))

Output

10 0.8271
50 0.8579
100 0.8559

Why: the AUC rises steeply from 10 to 50 trees; from 50 to 100 it stays about the same and can move a little up or down. The curve flattens.

Problem 12: The OOB score

Train a forest with oob_score=True and random_state=42. Print its OOB score and its test accuracy, rounded to 4 decimals.

Idea. The out-of-bag rows give a validation score without the test data (Part 8).

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

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

Output

0.8599
0.8604

Why: the two numbers are close: the OOB score is an honest estimate.

Problem 13: The tuned forest

Train a forest with max_depth=10 and random_state=42, called tuned. Print its test accuracy and its test AUC, rounded to 4 decimals.

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

Python, continues from the cells above
tuned = RandomForestClassifier(max_depth=10, random_state=42)
tuned.fit(X_train, y_train)

print(round(tuned.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1]), 4))

Output

0.864
0.8659

Why: limiting the depth of every tree smooths the probabilities and raises the AUC a little.

Problem 14: Permutation importance

Compute the permutation importance of tuned on the test data with n_repeats=5 and random_state=42. Print the three most important features, rounded to 4 decimals.

Idea. Shuffle each column and measure the drop of the accuracy (Part 7).

Python, continues from the cells above
from sklearn.inspection import permutation_importance

result = permutation_importance(tuned, X_test, y_test, n_repeats=5, random_state=42)
permuted = pd.Series(result.importances_mean, index=X.columns)

print(permuted.sort_values(ascending=False).head(3).round(4))

Output

age                0.0703
products_number    0.0523
active_member      0.0347
dtype: float64

Why: the same three features as in the lesson: the age, the number of products and the activity.

Problem 15: Bagged trees

Train a single full DecisionTreeClassifier with random_state=42, and a BaggingClassifier of 100 full trees with random_state=42. Print the test AUC of each, rounded to 4 decimals.

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

Python, continues from the cells above
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier

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

bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)
bagged_trees.fit(X_train, y_train)

print(round(roc_auc_score(y_test, full_tree.predict_proba(X_test)[:, 1]), 4))
print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))

Output

0.6864
0.845

Why: one full tree ranks badly; a hundred bagged full trees rank almost as well as the forest.

Problem 16: Bagged logistic regression

Scale the features with a StandardScaler fitted on the training data. Train a LogisticRegression and a BaggingClassifier of 100 logistic regressions with random_state=42. Print the test AUC of each, rounded to 4 decimals.

Idea. Bagging around a stable model, which needs scaled data (Part 9).

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

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

logistic = LogisticRegression()
logistic.fit(X_train_scaled, y_train)

bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)
bagged_logistic.fit(X_train_scaled, y_train)

print(round(roc_auc_score(y_test, logistic.predict_proba(X_test_scaled)[:, 1]), 4))
print(round(roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1]), 4))

Output

0.7713
0.7717

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 Bank Customer Churn Prediction.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the file to bagged models. Under every problem there is a hint and a solution.

13.1Group A: by hand

  1. 1.A bootstrap sample of size 4 is drawn from the customers P, Q, R, S: Q, Q, S, P. (a) Which customer is out of bag? (b) What is the probability that a given customer is left out of a bootstrap sample of size 4? Give 3 decimals.

    Show a hint
    In one draw a customer is missed with the probability 34\frac{3}{4}.
    Show one possible solution

    Answer: (a) R; (b) 0.316.

    0.754=0.3160.75^4 = 0.316

    R was never drawn; Q was drawn twice.

  2. 2.Five trees give a customer the probabilities of leaving 0.2, 0.6, 0.3, 0.1 and 0.4. (a) What probability does the forest give? (b) Which class does it predict? (c) How many trees alone would say "leaves"?

    Show a hint
    The mean of the probabilities; a tree says "leaves" when its probability is at least 0.5.
    Show one possible solution

    Answer: (a) 0.32; (b) stays; (c) 1.

    0.2+0.6+0.3+0.1+0.45=1.65=0.32\frac{0.2 + 0.6 + 0.3 + 0.1 + 0.4}{5} = \frac{1.6}{5} = 0.32

    0.32 is below 0.5: stays. Only the tree with 0.6 says "leaves".

  3. 3.Three independent models are each right with the probability 0.6. How often is their majority right? Give 3 decimals.

    Show a hint
    All three right, or exactly two right: p3+3×p2×(1−p)p^3 + 3 \times p^2 \times (1 - p).
    Show one possible solution

    Answer: 0.648.

    0.63=0.2163×0.62×0.4=3×0.36×0.4=0.4320.216+0.432=0.648\begin{aligned} 0.6^3 &= 0.216 \\[4pt] 3 \times 0.6^2 \times 0.4 &= 3 \times 0.36 \times 0.4 = 0.432 \\[4pt] 0.216 + 0.432 &= 0.648 \end{aligned}
  4. 4.(a) A data set has 16 features. How many features does each split of a default RandomForestClassifier try? (b) Does a forest need scaled features? (c) Does bagging help logistic regression much?

    Show a hint
    The square root; trees compare values with thresholds; bagging cures variance.
    Show one possible solution

    Answer: (a) 4; (b) no; (c) no.

    16=4\sqrt{16} = 4

    A forest's trees only compare values with thresholds. Logistic regression is stable, so its bagged copies are almost the same model.

13.2Group B: one project in Python

The same workflow as in the lesson, on the same file, with another split: test_size=0.3 with random_state=1. 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 file to the data for the forest

Read the file, drop and encode, split. No scaling for a forest.

  1. 5.Read Bank Customer Churn Prediction.csv into df. Print the shape, then the number of customers who left.
    Show a hint
    df = pd.read_csv("Bank Customer Churn Prediction.csv"), then print(df.shape) and print(df["churn"].sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("Bank Customer Churn Prediction.csv")
    
    print(df.shape)
    print(df["churn"].sum())

    Output

    (10000, 12)
    2037
  2. 6.Drop the column customer_id and encode gender as 0 (Female) and 1 (Male). Print the number of women. This step continues from Step 5.
    Show a hint
    df = df.drop(columns=["customer_id"]) and df["gender"] = df["gender"].map({"Female": 0, "Male": 1}). The women are the rows with 0: print((df["gender"] == 0).sum()).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop(columns=["customer_id"])
    df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
    
    print((df["gender"] == 0).sum())

    Output

    4543
  3. 7.One-hot encode country inside the table, with drop_first=True and dtype=int. Print the number of columns. This step continues from Step 6.
    Show a hint
    df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int), then print(len(df.columns)).
    Show one possible solution
    Python, continues from the cells above
    df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)
    
    print(len(df.columns))

    Output

    12
  4. 8.Make X (all columns without churn) and y (churn). Split them with test_size=0.3 and random_state=1. Print the number of test customers, then how many of them left. This step continues from Step 7.
    Show a hint
    X = df.drop(columns=["churn"]), y = df["churn"], X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1), then print(len(y_test)) and print(y_test.sum()).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["churn"])
    y = df["churn"]
    
    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(y_test.sum())

    Output

    3000
    627

Steps 9 to 12: the random forest and its measures

The default forest, its trees, the confusion matrix, recall, F1 and AUC.

  1. 9.Train a RandomForestClassifier called forest with random_state=42. Print its test accuracy, rounded to 4 decimals. This step continues from Step 8.
    Show a hint
    forest = RandomForestClassifier(random_state=42), forest.fit(X_train, y_train), then print(round(forest.score(X_test, y_test), 4)).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.ensemble import RandomForestClassifier
    
    forest = RandomForestClassifier(random_state=42)
    forest.fit(X_train, y_train)
    
    print(round(forest.score(X_test, y_test), 4))

    Output

    0.862
  2. 10.Print the number of trees in forest, then the depth of its first tree. This step continues from Step 9.
    Show a hint
    print(len(forest.estimators_)) and print(forest.estimators_[0].get_depth()).
    Show one possible solution
    Python, continues from the cells above
    print(len(forest.estimators_))
    print(forest.estimators_[0].get_depth())

    Output

    100
    22
  3. 11.Put the test predictions of forest into predicted and print the confusion matrix. This step continues from Step 9.
    Show a hint
    predicted = forest.predict(X_test), then print(confusion_matrix(y_test, predicted)): the truth first.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import confusion_matrix
    
    predicted = forest.predict(X_test)
    
    print(confusion_matrix(y_test, predicted))

    Output

    [[2290   83]
     [ 331  296]]
  4. 12.Print the recall, the F1-score and the AUC of forest, in this order, each rounded to 4 decimals. This step continues from Step 11.
    Show a hint
    recall_score and f1_score with (y_test, predicted); roc_auc_score with the probabilities forest.predict_proba(X_test)[:, 1].
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import recall_score, f1_score, roc_auc_score
    
    print(round(recall_score(y_test, predicted), 4))
    print(round(f1_score(y_test, predicted), 4))
    print(round(roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1]), 4))

    Output

    0.4721
    0.5885
    0.8585

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

The out-of-bag score, a tuned forest, bagged trees, and bagged logistic regression on scaled data with a chart.

  1. 13.Train a forest with oob_score=True and random_state=42. Print its OOB score, rounded to 4 decimals. This step continues from Step 9.
    Show a hint
    oob_forest = RandomForestClassifier(oob_score=True, random_state=42), fit, then print(round(oob_forest.oob_score_, 4)).
    Show one possible solution
    Python, continues from the cells above
    oob_forest = RandomForestClassifier(oob_score=True, random_state=42)
    oob_forest.fit(X_train, y_train)
    
    print(round(oob_forest.oob_score_, 4))

    Output

    0.8583
  2. 14.Train a forest with max_depth=10 and random_state=42. Print its test AUC rounded to 4 decimals, then the name of its most important feature by impurity importance. This step continues from Step 12.
    Show a hint
    tuned = RandomForestClassifier(max_depth=10, random_state=42), fit, roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1]), then pd.Series(tuned.feature_importances_, index=X.columns).idxmax().
    Show one possible solution
    Python, continues from the cells above
    tuned = RandomForestClassifier(max_depth=10, random_state=42)
    tuned.fit(X_train, y_train)
    
    print(round(roc_auc_score(y_test, tuned.predict_proba(X_test)[:, 1]), 4))
    print(pd.Series(tuned.feature_importances_, index=X.columns).idxmax())

    Output

    0.8668
    age
  3. 15.Train a BaggingClassifier of 100 full decision trees with random_state=42, called bagged_trees. Print its test accuracy and its test AUC, each rounded to 4 decimals. This step continues from Step 12.
    Show a hint
    bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42), fit, then score and roc_auc_score with predict_proba(X_test)[:, 1].
    Show one possible solution
    Python, continues from the cells above
    from sklearn.ensemble import BaggingClassifier
    from sklearn.tree import DecisionTreeClassifier
    
    bagged_trees = BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42)
    bagged_trees.fit(X_train, y_train)
    
    print(round(bagged_trees.score(X_test, y_test), 4))
    print(round(roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]), 4))

    Output

    0.8527
    0.8453
  4. 16.Scale the features (StandardScaler fitted on the training data), train a BaggingClassifier of 100 logistic regressions with random_state=42 on the scaled data, and print its test AUC rounded to 4 decimals. Then draw the test AUC of forest, bagged_trees and this model as horizontal bars. This step continues from Step 15.
    Show a hint
    scaler.fit_transform(X_train) and scaler.transform(X_test); BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42); then plt.barh(names, aucs) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import matplotlib.pyplot as plt
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    
    bagged_logistic = BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42)
    bagged_logistic.fit(X_train_scaled, y_train)
    
    auc_logistic = roc_auc_score(y_test, bagged_logistic.predict_proba(X_test_scaled)[:, 1])
    print(round(auc_logistic, 4))
    
    names = ["random forest", "bagged trees", "bagged logistic regression"]
    aucs = [
        roc_auc_score(y_test, forest.predict_proba(X_test)[:, 1]),
        roc_auc_score(y_test, bagged_trees.predict_proba(X_test)[:, 1]),
        auc_logistic,
    ]
    
    plt.barh(names, aucs)
    plt.xlabel("test AUC")
    plt.show()

    Output

    0.7673
    The chart this code draws

14Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.What is a random forest?

Question 2

2.What is a bootstrap sample?

Question 3

3.About which share of the training rows is out of bag for one tree, on large data?

Question 4

4.Why does a random forest try only a few random features at each split?

Question 5

5.How does scikit-learn's RandomForestClassifier decide for a new row?

Question 6

6.What happens when n_estimators is raised from 100 to 1,000?

Question 7

7.Which score does a tree inside a random forest use to choose its questions?

Question 8

8.What is the OOB score?

Question 9

9.Why can the impurity importance of a forest mislead?

Question 10

10.Bagging around logistic regression gave almost the same scores as one logistic regression. Why?

Question 11

11.Which setting turns a random forest into plain bagging of trees?

Question 12

12.Does a random forest need scaled features?

0 of 12 answered.

15Summary

Summary
Formula or ruleMeaning
Bootstrap samplenn rows drawn with replacementabout 63 percent of the rows, some several times
Left out of one sample(1−1n)n\left(1 - \tfrac{1}{n}\right)^{n}, about 1e=0.368\frac{1}{e} = 0.368the out-of-bag rows
Features per splitp\sqrt{p} by defaultrandom, for every split
The forest's probabilitythe mean of the trees' probabilitiesthe class with the larger mean
Majority of three, each right with ppp3+3×p2×(1−p)p^3 + 3 \times p^2 \times (1 - p)higher than pp if p>0.5p > 0.5 and the mistakes are independent
Variance of an average of nn modelsρ σ2+(1−ρ) σ2n\rho \, \sigma^2 + \frac{(1 - \rho)\,\sigma^2}{n}more models shrink only the second part; less correlation shrinks the first
Random forestbagging of trees + random featuresless correlated trees, less variance
Summary
CodeWhat it does
RandomForestClassifier(random_state=42)a forest of 100 full trees
n_estimators, max_features, max_depth, min_samples_leafthe most used hyperparameters
oob_score=True, then oob_score_the out-of-bag accuracy
class_weight="balanced"more weight for the rare class
forest.estimators_the list of the trees
forest.feature_importances_the impurity importance, averaged over the trees
permutation_importance(model, X_test, y_test, n_repeats=5)the drop of the score when a column is shuffled
BaggingClassifier(estimator=..., n_estimators=100)bagging around any model

Rules to keep

  1. A random forest is many deep trees, each on a bootstrap sample and with random features at every split; it averages their probabilities.
  2. Each tree chooses its questions with the Gini impurity or the entropy, among a few random features.
  3. More trees never overfit; they only cost time. Tune max_features, max_depth and min_samples_leaf.
  4. The OOB score is a free validation; the test data judges the finished model.
  5. Check the impurity importances with the permutation importance.
  6. Bagging works around any model and cures variance: it helps deep trees a lot and stable models hardly at all.
  7. No scaling for forests and bagged trees; the model inside a bagging decides its own preprocessing.

What comes next

The forests of this lesson predicted a class. Topic 31 uses the same ideas, random forests and bagging, for a number as the target, with the measures of regression. Then Topic 32 brings a model that works in a completely different way: k-nearest neighbours, which looks at the most similar customers. It needs distances, so scaling becomes essential again. Naive Bayes, which calculates probabilities with Bayes' rule (Topic 16), follows in Topic 34.