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.
Lesson notebook
The lesson as a Jupyter notebook: the project on the bank data cell by cell, from the random forest to bagging and the scores of every model, and the sixteen solved problems.
topic-30-random-forests-and-bagging.ipynb, 79 KB
Practice notebook
The same project on the bank data in twelve steps, from reading the file to a forest, bagged models and their scores, with a hint and a hidden solution for each step.
topic-30-practice.ipynb, 19 KB
Data file: the bank customers
10,000 customers of a bank with 12 columns, the file of Topics 27 to 29: the data of the lesson, the solved problems and the practice. A public data set (Bank Customer Churn Dataset, Kaggle).
Bank Customer Churn Prediction.csv, 548 KB
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.What a random forest is, and where it is used
- 2.What an ensemble is, and why many models can be better than one
- 3.How a random forest builds its trees: bootstrap samples and random features
- 4.How the trees choose their questions, and how the forest makes its decision
- 5.The out-of-bag score, and two kinds of feature importance
- 6.The hyperparameters of
RandomForestClassifierand their roles - 7.What scaling, encoding, outliers and missing values mean for forests, and for the models still to come
- 8.Bagging around any model with
BaggingClassifier: around trees and around logistic regression - 9.A whole project: from the file to a tuned forest, bagged models, and the scores of all of them
| Word | Meaning |
|---|---|
| Ensemble | a model made of several models whose answers are combined |
| Random forest | an ensemble of decision trees, each trained on a bootstrap sample and with random features at each split |
| Bootstrap sample | a 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) rows | the training rows that a bootstrap sample did not draw |
| Bagging | bootstrap aggregating: train the same model on many bootstrap samples and combine the answers |
| Majority vote | the class that most models predict |
| Averaging probabilities | the mean of the probabilities of all models; scikit-learn's forest decides this way |
max_features | how many features each split may choose from |
| OOB score | the accuracy of the forest on its out-of-bag rows: a free validation score |
| Permutation importance | how 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:
| Family | How the models are made | How they are combined | Topic |
|---|---|---|---|
| Bagging | the same model on many bootstrap samples, in parallel | vote or average | this topic |
| Random forest | bagging of trees, plus random features at every split | average of the probabilities | this topic |
| Boosting | models trained one after another, each one correcting the mistakes of the ones before | a weighted sum | Topics 37 to 40 |
| Voting | a few different models (a tree, a logistic regression, ...) | vote or average | Topics 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 | Weaknesses |
|---|---|
| Usually much more accurate than one tree | No longer readable as a few rules: 100 trees |
| Overfits far less than one deep tree | Slower to train and to predict than one tree, and bigger in memory |
| Works well with default settings | Its feature importances can mislead (Part 7 shows how) |
| No scaling needed, robust to outliers | Like every tree, it cannot predict beyond the values of the training data (regression) |
| A free validation score: the OOB score | On some data, boosting (Topics 37 to 40) is more accurate |
Try it yourself
Show a hint
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.
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:
| Draw | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| Customer | C | A | F | C | J | F | D | I | F | H |
- 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:
For large data the share approaches . 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.
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:
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:
| Tree | Probability of leaving | Its own class |
|---|---|---|
| Tree 1 | 0.8 | leaves |
| Tree 2 | 0.3 | stays |
| Tree 3 | 0.6 | leaves |
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:
Three trees of 70 percent together reach 78.4 percent. With five trees:
- each tree right with 0.7
- each tree right with 0.6
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 (how much it would change with another training sample), and every two trees are correlated with the correlation (Topic 20). The variance of the average of trees is:
Take and 100 trees:
Three lessons are in this formula:
- More trees shrink only the second part, . With 100 trees it is already tiny, which is why the scores flatten after some hundred trees.
- The first part, , 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 (), a forest would be exactly as good as one tree.
- ρ = 0
- ρ = 0.3
- ρ = 0.6
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
Show a hint
Show the solution
Answer: (a) B and E; (b) 0.335; (c) 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:
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:
| Question | Gini 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
Show a hint
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
| Hyperparameter | Default | Role |
|---|---|---|
n_estimators | 100 | the 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. |
bootstrap | True | whether every tree gets a bootstrap sample. With False every tree sees all rows, and only the random features make the trees differ. |
max_samples | None | the size of each bootstrap sample (a number or a share). None: as many rows as the training data. |
oob_score | False | with True the forest scores itself on its 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. The trees do not depend on each other, so they can be trained in parallel. |
random_state | None | the seed for all random choices (samples and features): the same forest at every run. |
class_weight | None | "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
| Hyperparameter | Default | Role in a forest |
|---|---|---|
criterion | "gini" | the impurity measure of every tree: "gini" or "entropy" |
max_depth | None | the depth of every tree. The default grows full trees; a limit makes every tree simpler and the forest faster. |
min_samples_split | 2 | the smallest node that may still be split |
min_samples_leaf | 1 | the smallest leaf; larger leaves give smoother probabilities |
max_leaf_nodes | None | the largest number of leaves of every tree |
min_impurity_decrease | 0.0 | a split must lower the impurity at least this much |
ccp_alpha | 0.0 | cost-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;Noneturns the forest into bagging of trees.max_depthandmin_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
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
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.
| Model (topic) | Scaling | Encoding of text | Outliers in the features |
|---|---|---|---|
| Linear and logistic regression (22, 26, 27) | needed | needed | sensitive |
| Decision tree (29) | not needed | needed | robust |
| Random forest, bagged trees (30, 31) | not needed | needed | robust |
| Bagging around another model (30, 31) | as the model inside | as the model inside | as the model inside |
| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive |
| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive |
| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive |
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
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
| Measure | Full tree (Topic 29) | Tree with max_depth=5 (Topic 29) | Random forest |
|---|---|---|---|
| Accuracy | 0.7845 | 0.8575 | 0.867 |
| Precision | 0.4562 | 0.7647 | 0.7613 |
| Recall | 0.5038 | 0.3969 | 0.4707 |
| F1-score | 0.4788 | 0.5226 | 0.5818 |
| AUC | 0.6785 | 0.8328 | 0.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
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?
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
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()
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
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
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?
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.
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.
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()
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:
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
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 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
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.
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
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
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
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
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
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
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:
- Draw many bootstrap samples of the training data.
- Train the same kind of model on each sample.
- 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:
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:
| Hyperparameter | Default | Role |
|---|---|---|
estimator | a decision tree | the model inside, which is 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 accuracy, as in the forest |
random_state | None | the 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
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:
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.
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 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 pairs, so 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
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:
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)
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.
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
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.
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()
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
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
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
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |
| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |
| 3. Drop | columns without information | customer_id |
| 4. Target | the share of each class | 20 percent left: unbalanced |
| 5. Outliers | find them, decide | real customers, kept |
| 6. Encode | text to numbers | gender 0 and 1, country one-hot, products_number a number |
| 7. Split | training and test data | 8,000 and 2,000 |
| 8. Scale | only for the models that need it | not for the forest; for logistic regression and its bagging |
| 9. Model | the random forest | default: accuracy 0.867, AUC 0.856 |
| 10. Look inside | trees, votes, importances | permutation importance: age, products, activity |
| 11. Tune | n_estimators, max_depth (cross-validation), OOB score | max_depth=10: AUC 0.871 |
| 12. Model again | bagging around other models | trees gain, logistic regression does not |
| 13. Judge | the scores of every model on the same test data | the forest leads |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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).
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).
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).
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).
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).
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).
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.
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.
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.
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).
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).
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).
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).
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).
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).
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).
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.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 .Show one possible solution
Answer: (a) R; (b) 0.316.
R was never drawn; Q was drawn twice.
- 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.32 is below 0.5: stays. Only the tree with 0.6 says "leaves".
- 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: .Show one possible solution
Answer: 0.648.
- 4.(a) A data set has 16 features. How many features does each split of a default
RandomForestClassifiertry? (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.
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.
- 5.Read
Bank Customer Churn Prediction.csvintodf. Print the shape, then the number of customers who left.Show a hint
df = pd.read_csv("Bank Customer Churn Prediction.csv"), thenprint(df.shape)andprint(df["churn"].sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("Bank Customer Churn Prediction.csv") print(df.shape) print(df["churn"].sum())Output
(10000, 12) 2037
- 6.Drop the column
customer_idand encodegenderas 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"])anddf["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 abovedf = df.drop(columns=["customer_id"]) df["gender"] = df["gender"].map({"Female": 0, "Male": 1}) print((df["gender"] == 0).sum())Output
4543
- 7.One-hot encode
countryinside the table, withdrop_first=Trueanddtype=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), thenprint(len(df.columns)).Show one possible solution
Python, continues from the cells abovedf = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int) print(len(df.columns))Output
12
- 8.Make
X(all columns withoutchurn) andy(churn). Split them withtest_size=0.3andrandom_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), thenprint(len(y_test))andprint(y_test.sum()).Show one possible solution
Python, continues from the cells abovefrom 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.
- 9.Train a
RandomForestClassifiercalledforestwithrandom_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), thenprint(round(forest.score(X_test, y_test), 4)).Show one possible solution
Python, continues from the cells abovefrom 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
- 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_))andprint(forest.estimators_[0].get_depth()).Show one possible solution
Python, continues from the cells aboveprint(len(forest.estimators_)) print(forest.estimators_[0].get_depth())Output
100 22
- 11.Put the test predictions of
forestintopredictedand print the confusion matrix. This step continues from Step 9.Show a hint
predicted = forest.predict(X_test), thenprint(confusion_matrix(y_test, predicted)): the truth first.Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import confusion_matrix predicted = forest.predict(X_test) print(confusion_matrix(y_test, predicted))Output
[[2290 83] [ 331 296]]
- 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_scoreandf1_scorewith(y_test, predicted);roc_auc_scorewith the probabilitiesforest.predict_proba(X_test)[:, 1].Show one possible solution
Python, continues from the cells abovefrom 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.
- 13.Train a forest with
oob_score=Trueandrandom_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, thenprint(round(oob_forest.oob_score_, 4)).Show one possible solution
Python, continues from the cells aboveoob_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
- 14.Train a forest with
max_depth=10andrandom_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]), thenpd.Series(tuned.feature_importances_, index=X.columns).idxmax().Show one possible solution
Python, continues from the cells abovetuned = 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
- 15.Train a
BaggingClassifierof 100 full decision trees withrandom_state=42, calledbagged_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, thenscoreandroc_auc_scorewithpredict_proba(X_test)[:, 1].Show one possible solution
Python, continues from the cells abovefrom 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
- 16.Scale the features (
StandardScalerfitted on the training data), train aBaggingClassifierof 100 logistic regressions withrandom_state=42on the scaled data, and print its test AUC rounded to 4 decimals. Then draw the test AUC offorest,bagged_treesand this model as horizontal bars. This step continues from Step 15.Show a hint
scaler.fit_transform(X_train)andscaler.transform(X_test);BaggingClassifier(estimator=LogisticRegression(), n_estimators=100, random_state=42); thenplt.barh(names, aucs)andplt.show().Show one possible solution
Python, continues from the cells aboveimport 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

14Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
15Summary
| Formula or rule | Meaning | |
|---|---|---|
| Bootstrap sample | rows drawn with replacement | about 63 percent of the rows, some several times |
| Left out of one sample | , about | the out-of-bag rows |
| Features per split | by default | random, for every split |
| The forest's probability | the mean of the trees' probabilities | the class with the larger mean |
| Majority of three, each right with | higher than if and the mistakes are independent | |
| Variance of an average of models | more models shrink only the second part; less correlation shrinks the first | |
| Random forest | bagging of trees + random features | less correlated trees, less variance |
| Code | What it does |
|---|---|
RandomForestClassifier(random_state=42) | a forest of 100 full trees |
n_estimators, max_features, max_depth, min_samples_leaf | the 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
- A random forest is many deep trees, each on a bootstrap sample and with random features at every split; it averages their probabilities.
- Each tree chooses its questions with the Gini impurity or the entropy, among a few random features.
- More trees never overfit; they only cost time. Tune
max_features,max_depthandmin_samples_leaf. - The OOB score is a free validation; the test data judges the finished model.
- Check the impurity importances with the permutation importance.
- Bagging works around any model and cures variance: it helps deep trees a lot and stable models hardly at all.
- 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.