Module 3, topic 29, week 15, Tuesday
Decision Trees
A model made of yes-or-no questions: how a tree decides, how it chooses each question with the Gini impurity and the entropy, regression trees, the hyperparameters that stop it from overfitting, what preprocessing it needs, and a whole project on the bank data from the file to a tuned and explained tree.
Lesson notebook
The lesson as a Jupyter notebook: the worked example, the project on the bank data cell by cell with the drawn trees and charts, and the sixteen solved problems.
topic-29-decision-trees.ipynb, 79 KB
Practice notebook
The same project on the bank data in twelve steps, from reading the file to a tuned tree and its picture, with a hint and a hidden solution for each step.
topic-29-practice.ipynb, 19 KB
Data file: the bank customers
10,000 customers of a bank with 12 columns, the file of Topics 27 and 28: 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: a model made of questions
The ninth lesson of Module 3. Every model so far calculated a weighted sum of the features: linear regression, Ridge and Lasso, logistic regression. A decision tree works in a completely different way. It asks a row of simple yes-or-no questions about a customer ("Is the customer older than 44?", "Is he an active member?") and gives the answer that was most common among similar customers in the training data. It is the model that is easiest to explain to a person who has never heard of machine learning, and it is the building block of the strongest models of this module: random forests (Topic 30) and boosting (Topics 37 to 40).
The lesson has two halves. The first is done on paper: what a tree is and where it is used, how it makes a decision, how it chooses its first question and every question after it (Gini impurity and entropy), regression trees, the hyperparameters, and what scaling, encoding, outliers and missing values mean for trees and for the models still to come. The second half is the project on Bank Customer Churn Prediction.csv, the file of Topics 27 and 28: every step from reading the file to a tuned tree and its measures, explained once more as a real workflow.
You need: the workflow of a project (Topics 21 and 27), the train/test split and cross-validation (Topic 23), overfitting and underfitting (Topic 23), encoding (Topic 25), predict_proba and the threshold (Topic 27), and the measures of a classifier (Topic 28).
What you will learn
- 1.What a decision tree is, its parts, and the tasks it is used for
- 2.How a tree makes a decision for a new row
- 3.How a tree chooses its first question and every question after it: Gini impurity, entropy and information gain
- 4.How a numerical column is split, and how a regression tree works
- 5.Why a tree overfits, and the hyperparameters that stop it
- 6.What scaling, encoding, outliers and missing values mean for trees, and for the models still to come
- 7.A whole project with
DecisionTreeClassifier: from the file to a tuned tree, its rules, its feature importances and its measures
| Word | Meaning |
|---|---|
| Decision tree | a model that predicts by asking a row of yes-or-no questions about the features |
| Node | one question of the tree, or one end of it |
| Root node | the first question, at the top; all training rows start there |
| Branch | the way from a question to the next node: "yes" or "no" |
| Internal node | a node with a question, between the root and the leaves |
| Leaf | a node without a question: here the tree gives its answer |
| Depth | the number of questions on the longest way from the root to a leaf |
| Split | dividing the rows of a node into two groups with one question |
| Impurity | how mixed the classes in a node are: 0 when all rows have the same class |
| Gini impurity | an impurity measure: the chance that two rows drawn at random from the node have different classes |
| Entropy | another impurity measure, from information theory |
| Information gain | how much a split lowers the impurity |
| Pruning | limiting or cutting back a tree so that it does not learn the noise |
| Feature importance | how much a feature lowered the impurity, summed over all its splits |
1What a decision tree is
1.1A row of questions
Think of the game "twenty questions": one person thinks of an animal, the other may only ask yes-or-no questions. A good player does not start with "Is it a cat?". He asks a question that cuts the possibilities roughly in half: "Does it live in water?". Each answer leads to the next question, until the answer is clear.
A decision tree plays this game with data. For a bank customer it might ask:
- Is the customer older than 44?
- If yes: is he an active member?
- If no: does he have more than 2 products?
and at the end it says "leaves" or "stays". The questions are not written by a person: the tree learns them from the training data, and it learns which question to ask first.
1.2The parts of a tree
- The root node holds the first question. All training rows start there.
- An internal node holds a later question. It receives only the rows that took its branch.
- A leaf holds no question. It holds the answer: the class that was most common among the training rows that ended there.
- The depth of this tree is 2: every way from the root to a leaf passes two questions.
The tree is drawn upside down, with the root at the top. That is the custom in machine learning.
1.3Classification and regression
Decision trees solve both kinds of supervised tasks (Topic 21):
| Classification tree | Regression tree | |
|---|---|---|
| The target | a class: leaves or stays, spam or not | a number: a price, a balance, a mark |
| A leaf answers with | the most common class of its rows (and their shares as probabilities) | the mean of the target of its rows |
| A split is chosen by | the impurity of the classes (Gini, entropy) | the squared error |
| scikit-learn | DecisionTreeClassifier | DecisionTreeRegressor |
This lesson works mainly with classification, on the bank data. Part 4 shows the regression tree on a small example.
1.4Where trees are used
- Banking and credit: who will not pay back a loan, which customer is about to leave, which payment looks like fraud. A bank must often explain a decision to its customer or its supervisor, and the rules of a tree can be read aloud.
- Medicine: rules for triage ("breathing rate above 30? blood pressure below 90?"), the risk of a disease from a few measurements.
- Business: which customers answer an offer, which product a customer buys next.
- Industry: which part of a machine will fail, from its sensor values.
- As a building block: one tree alone is a good but rarely the best model. Hundreds of trees together are among the strongest models for tables of data: random forests (Topic 30) and gradient boosting (Topics 37 to 40). Whatever you learn about one tree today, you will use there.
1.5Strengths and weaknesses
| Strengths | Weaknesses |
|---|---|
| Easy to explain: every prediction is a short row of rules | A single tree overfits easily: it can learn the training rows by heart |
| No scaling needed (Part 6) | Unstable: a few different training rows can give a quite different tree |
| Handles numbers and categories, and effects that are not in order | Its borders are always straight steps; smooth relationships need many steps |
| Finds interactions by itself ("old and not active") | It is greedy: it takes the best question now, not the best tree overall |
| Fast to train and to predict | Its probabilities are coarse: the shares of a few leaves |
Try it yourself
Show a hint
Show the solution
Answer: (a) 2; (b) the root node; (c) the answer; (d) a regression tree.
Every way passes two questions, so the depth is 2. The first question sits in the root node at the top. A leaf has no question: it gives the answer. A price is a number, so a regression tree predicts it, with the mean of the rows in each leaf.
2How a tree makes a decision
2.1Following the path
A trained tree predicts for a new row by walking from the root to a leaf. Take the tree of Part 1 and a customer who is 52 years old and not an active member:
- Root: is the age above 44? 52 is above 44: yes, go right.
- Next question: is he an active member? No, go left.
- A leaf: leaves.
A second customer, 30 years old with 1 product:
- Is the age above 44? No, go left.
- More than 2 products? No, go left.
- A leaf: stays.
Every prediction asks only as many questions as the tree is deep. The tree never adds or multiplies the features: it only compares one feature with one number at a time.
2.2The probability from a leaf
Every leaf remembers how many training rows of each class ended there. Suppose the leaf "older than 44, not active" received 400 training customers, and 260 of them left. Then for every new customer who reaches this leaf:
predict_proba returns exactly this share, and predict gives the class with the larger share (here "leaves", because 0.65 is above 0.5). All customers in the same leaf get the same probability. A tree with 8 leaves can give at most 8 different probabilities: much coarser than logistic regression, which gives every customer his own.
2.3The tree as a picture of the data
Each question cuts the data along one feature, at one value. Two questions on two features cut the plane of these two features into rectangles, and every rectangle gets one class. A tree draws its borders only parallel to the axes: in steps, never diagonally. Logistic regression draws one straight border in any direction (Topic 27). Which is better depends on the data.
Try it yourself
predict give him?Show a hint
Show the solution
Answer: (a) stays; (b) leaves; (c) 0.4; (d) stays.
(a) 60 is above 44, and he is active: stays. (b) 35 is not above 44, and 3 products are more than 2: leaves. (c) and (d): 0.4 is below 0.5, so predict says stays.
3How a tree chooses its questions
3.1The goal: pure groups
A question is good when it separates the classes: after the split each group should contain mostly one class. A group with only one class is pure. The tree needs a number for "how mixed is this group?": an impurity measure. scikit-learn offers two for classification.
3.2Gini impurity
For a node in which a share of the rows belongs to class 1 and to class 0:
It is the chance that two rows, drawn at random from the node, have different classes.
- A pure node ( or ): .
- The most mixed node, half and half (): , the largest value for two classes.
3.3Entropy
It comes from information theory: the number of yes-or-no questions (bits) needed, on average, to tell the class of a row. A pure node has entropy 0, a half-and-half node has entropy 1 (one question is needed).
- Gini impurity
- entropy
Both curves have the same shape: zero at the ends, highest in the middle. They almost always choose the same questions. Gini is the default of scikit-learn because it needs no logarithm and is a little faster.
3.4The impurity of a split
A split makes two groups. Its impurity is the mean of the two impurities, weighted by the size of the groups:
The tree tries every possible question and takes the one with the lowest impurity after the split. With entropy, the drop of the impurity is called the information gain:
3.5A worked example: ten customers
Ten customers of a bank. For each we know three yes-or-no facts and whether he left:
| Customer | Over 50 | Active member | Two or more products | Left |
|---|---|---|---|---|
| A | yes | no | no | yes |
| B | yes | no | no | yes |
| C | yes | no | yes | yes |
| D | yes | yes | yes | no |
| E | no | yes | no | yes |
| F | no | yes | no | no |
| G | no | yes | yes | no |
| H | no | yes | no | no |
| I | no | no | yes | no |
| J | no | no | no | no |
4 of the 10 customers left, 6 stayed.
Step 1: the impurity of the root. All ten customers are in the root, and :
Step 2: try every question. Each question splits the ten customers into two groups. For each group: count, Gini, then the weighted mean.
Question "Over 50?": yes = A, B, C, D (3 left of 4); no = E to J (1 left of 6).
Question "Active member?": yes = D, E, F, G, H (1 left of 5); no = A, B, C, I, J (3 left of 5).
Question "Two or more products?": yes = C, D, G, I (1 left of 4); no = A, B, E, F, H, J (3 left of 6).
Choose a question and see how it splits the ten customers. The lower the Gini after the split, the better the question.
yes: 4 customers, 3 left
A leftB leftC leftD stayed
Gini 0.375
no: 6 customers, 1 left
E leftF stayedG stayedH stayedI stayedJ stayed
Gini 0.278
Gini after the split = 4/10 × 0.375 + 6/10 × 0.278 = 0.317, down from 0.48.
Squares left, circles stayed. Try all three yes-or-no questions, then the ages: which threshold beats "Over 50?"?
Step 3: choose.
| Question | Gini after the split | Drop from 0.48 |
|---|---|---|
| Over 50? | 0.317 | 0.163 |
| Active member? | 0.40 | 0.08 |
| Two or more products? | 0.45 | 0.03 |
"Over 50?" lowers the impurity most. It becomes the root node.
Step 4: repeat in each group. The tree now does exactly the same inside each of the two groups, with only their rows.
The group "over 50" (A, B, C, D: 3 left, 1 stayed). "Active member?" splits it into A, B, C (all left) and D (stayed): two pure groups, Gini 0 after the split. "Two or more products?" gives A, B (both left) and C, D (one each): Gini 0.25 after the split. So the question here is "Active member?", and both new nodes are pure: they become leaves, "leaves" and "stays".
The group "50 or younger" (E to J: 1 left, 5 stayed) is nearly pure. Whichever question splits it, every new group still has more customers who stayed, so every leaf would say "stays". The tree can stop here: the node becomes a leaf, "stays".
The finished tree:
- Over 50? No: stays (5 of 6 stayed).
- Over 50? Yes, active member? No: leaves (3 of 3 left).
- Over 50? Yes, active member? Yes: stays (1 of 1 stayed).
Step 5: the same with entropy. The root has . With and :
For "Over 50?", with , , and :
The other two questions give a smaller information gain, so entropy chooses the same root as Gini. This is the usual case.
3.6Numerical columns: trying every threshold
The example had yes-or-no columns. A real column such as age has many values. The tree then tries questions of the form "?" for many thresholds . It sorts the values and tries the points half way between two neighbouring values.
The real ages of the ten customers, from the youngest:
| Customer | I | F | E | H | G | J | D | B | C | A |
|---|---|---|---|---|---|---|---|---|---|---|
| Age | 25 | 29 | 34 | 38 | 41 | 45 | 51 | 55 | 58 | 62 |
| Left | no | no | yes | no | no | no | no | yes | yes | yes |
Between 45 and 51 lies the threshold 48: "age > 48?" gives the same groups as "Over 50?", with Gini 0.317. But between 51 and 55 lies 53, and "age > 53?" puts B, C and A together, all three of whom left:
The ten customers by age
squares left, circles stayed
Gini after the split
the lowest wins
With the real ages the tree finds a better question than "Over 50?". Of the nine thresholds, 53 gives the lowest impurity. This is how DecisionTreeClassifier works on every numerical column: it tries the thresholds of every feature and keeps the single best pair of feature and threshold.
3.7How the tree grows, and when it stops
The whole algorithm in four sentences:
- Start with all training rows in the root.
- Try every feature and every threshold; take the split with the lowest impurity after the split.
- Do the same again in each of the two new nodes, with their rows only.
- Stop in a node when it is pure, or when a limit is reached (a maximal depth, too few rows to split: Part 5). The node becomes a leaf.
Two properties of this algorithm explain much of the behaviour of trees:
- It is greedy: at each node it takes the best question for this moment. It never goes back to ask whether a weaker first question would have allowed better questions later. Finding the best tree overall would take far too long.
- Without limits it grows until every leaf is pure. On real data, where two customers with the same features can behave differently, that means leaves with one or two customers each: the tree learns the training rows by heart. Part 5 is about this.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.5; (b) 1; (c) 0; (d) yes, the best possible.
The impurity falls from its highest value to 0: the question separates the classes perfectly.
4Regression trees
A regression tree predicts a number. It grows in the same way; only two things change:
- A leaf answers with the mean of the target of its training rows.
- A split is judged by the squared error (the mean squared error, Topic 22) of the two groups, each around its own mean. The tree takes the split with the lowest weighted squared error.
A small example: six customers, their age and their balance in thousands.
| Age | 25 | 30 | 35 | 50 | 55 | 60 |
|---|---|---|---|---|---|---|
| Balance | 10 | 20 | 30 | 100 | 110 | 120 |
Without a split the tree predicts the mean, 65, for everybody:
With the question "age > 42.5?" (half way between 35 and 50):
One question lowers the mean squared error from 2091.7 to 66.7. The prediction of a regression tree is always a step function: a constant number in every leaf. It can never predict a value above the largest or below the smallest target of the training data.
In scikit-learn the regression tree is DecisionTreeRegressor; its hyperparameters are the same as those of Part 5. The bank project of this lesson is a classification, so the code uses DecisionTreeClassifier.
Try it yourself
Show a hint
Show the solution
Answer: (a) 60; (b) no.
Every prediction is a mean of training targets, so it never leaves their range.
5Overfitting and the hyperparameters
5.1Why a tree overfits
A tree without limits keeps asking questions until every leaf is pure. On the bank data it grows to a depth of more than 20 with more than a thousand leaves (Part 8 shows it). Its training accuracy is then 1.0: it knows every training customer by heart, including the noise. Its test accuracy is clearly lower. This is overfitting (Topic 23): low bias, very high variance. A small change of the training data would give a quite different tree.
The cure is to limit the tree: stop it early (pre-pruning), or let it grow and cut it back afterwards (post-pruning). The hyperparameters of DecisionTreeClassifier do exactly this.
5.2The hyperparameters of DecisionTreeClassifier
| Hyperparameter | Default | What it does | Effect of a larger value |
|---|---|---|---|
criterion | "gini" | the impurity measure: "gini", "entropy" (or "log_loss", the same as entropy) | (a choice, not a size) |
max_depth | None (no limit) | the largest number of questions from the root to a leaf | a deeper, more complex tree: more overfitting |
min_samples_split | 2 | the smallest number of rows a node must have to be split | fewer splits: a simpler tree |
min_samples_leaf | 1 | the smallest number of rows every leaf must keep | fewer, larger leaves: a simpler tree, smoother probabilities |
max_leaf_nodes | None | the largest number of leaves; the best splits are kept | a more complex tree |
min_impurity_decrease | 0.0 | a split is made only if it lowers the weighted impurity by at least this much | fewer splits: a simpler tree |
max_features | None (all) | how many features are tried at each split, chosen at random | None tries them all; a smaller number makes the tree more random (used in random forests, Topic 30) |
class_weight | None | weights for the classes; "balanced" gives the rare class more weight, as in Topic 27 | (a choice) more recall for the rare class |
ccp_alpha | 0.0 | cost-complexity pruning: after growing, branches that help too little are cut; a larger value cuts more | a smaller tree: less overfitting |
splitter | "best" | "best" tries all thresholds; "random" draws them at random | (a choice) |
random_state | None | the seed for the random choices, so that the tree is the same at every run | (no effect on quality) |
Five of them matter most in practice:
max_depth: the simplest and most used limit. A depth of 3 to 8 is common for a single tree.min_samples_leaf: every leaf must contain at least this many training rows. A leaf of 50 customers gives a reliable share; a leaf of 1 customer gives 0 or 1.criterion: Gini or entropy; the difference is usually small.class_weight: for unbalanced classes, when the recall of the rare class matters (Topic 28).ccp_alpha: post-pruning. The tree is grown fully, then the branches whose improvement is worth less thanccp_alphaper leaf are cut back.
Why random_state, when the algorithm is not random? When two features give exactly the same improvement, the tree must pick one, and scikit-learn shuffles the features before it tries them. With a fixed random_state the tree is the same at every run, and so are the numbers in this lesson.
5.3Choosing the hyperparameters
A hyperparameter is chosen with cross-validation on the training data, never with the test data (Topic 23): try a few values, keep the one with the best mean score over the folds, then judge the finished tree once on the test data. Part 9 does this for max_depth. A systematic search over several hyperparameters at once is the subject of Topic 42.
Try it yourself
max_depth gives the simpler tree: 3 or 10? (b) Does a larger min_samples_leaf give more leaves or fewer? (c) A larger ccp_alpha cuts more or less? (d) Which hyperparameter gives the rare class more weight?Show a hint
Show the solution
Answer: (a) 3; (b) fewer; (c) more; (d) class_weight.
Fewer questions, larger leaves and stronger pruning all make the tree simpler. class_weight="balanced" gives mistakes on the rare class more weight.
6Preprocessing for trees, and for the models still to come
Every project so far prepared the data in the same steps: fill or drop missing values, look at outliers, encode text, scale. Not every model needs every step. Knowing why a step is needed tells you when it can be left out.
6.1Scaling: not needed
A tree asks "is balance above 57,003?". If the balance were measured in thousands, the question would be "is balance above 57.003?": the same customers go left and right. Scaling (Topic 24) changes the numbers, not their order, so every split, every leaf and every prediction stays the same. Part 9 shows it in code. Scaling a tree's features does no harm; it is just unnecessary work.
Linear and logistic regression needed scaling for two reasons: the penalty of the regularization treats all weights alike (Topic 26), and the solver walks faster on features of the same scale (Topic 27). A tree has neither weights nor a solver.
6.2Encoding: still needed
scikit-learn's trees accept only numbers, so the text columns gender and country must still be encoded (Topic 25). Two remarks:
- A tree is not troubled by the order that label encoding invents. If
countrywere coded France , Germany , Spain , the tree could isolate Germany with two questions ("?" and "?"). One-hot encoding is still clearer, and this lesson keeps it. - A numerical column whose effect is not in order, such as
products_number, needed one-hot encoding for logistic regression (Topic 27: customers with 2 products leave least, with 1 product more, with 3 or 4 almost all). A tree handles it as it is: "products ≤ 1.5?" and "products > 2.5?" carve out the groups. This lesson keepsproducts_numberas a number.
6.3Outliers: trees are robust
A split depends only on the order of the values. A customer aged 92 ends up in the same branch as a customer aged 70 when the question is "age > 44?"; how far he lies beyond the others does not matter. So extreme values of the features do not pull a tree as they pull a regression line. They are still looked at (Topic 25): a value that is a mistake must be corrected or removed for any model.
Extreme values of the target do matter for a regression tree: a leaf predicts the mean of its rows, and one extreme value moves the mean.
6.4Missing values
scikit-learn's decision trees (since version 1.3) can work with missing values: at each split they also learn to which side a missing value should go. Most other models of scikit-learn stop with an error. In this course the habit stays the same for every model: look at the missing values first (Topic 11), understand why they are missing, then fill or drop them on purpose. The bank file has none.
6.5Unbalanced classes
A tree, like every model, is pulled towards the large class. class_weight="balanced" works for trees as it did for logistic regression (Topics 27 and 28). Topic 41 is about unbalanced data.
6.6A table for this and the coming topics
| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values in scikit-learn |
|---|---|---|---|---|
| Linear and logistic regression, Ridge, Lasso (22, 26, 27) | needed | needed | sensitive | must be filled |
| Decision tree (29) | not needed | needed | robust | handled since version 1.3 |
| Random forest (30, 31) | not needed | needed | robust | see Topic 30 |
| k-nearest neighbours (32, 33) | essential: distances | needed | sensitive | must be filled |
| Support vector machines (35, 36) | essential: distances | needed | sensitive | must be filled |
| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost and LightGBM handle them |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | must be filled |
The rule behind the table: models built from trees only compare a feature with a threshold, so they do not need scaling and do not mind outliers. Models built from distances, weights or variances need features on the same scale. Topic 42 will show how to put all preprocessing steps and the model into one object, so that none of them is forgotten.
Does this model need scaled features?
1 of 8
A decision tree (Topic 29)
Try it yourself
country be encoded before a tree of scikit-learn can use it? (c) A customer's age is 92. Does this outlier pull a tree's question as it pulls a regression line? (d) Which model of the coming topics needs scaling: random forests or k-nearest neighbours?Show a hint
Show the solution
Answer: (a) no; (b) yes; (c) no; (d) k-nearest neighbours.
Scaling keeps the order of the values, so a tree makes the same splits. scikit-learn's trees need numbers, so text is still encoded. An extreme age only lands in the last group of a question. k-nearest neighbours compares distances, and distances need features on the same scale; random forests are made of trees.
7The project: from the file to the data for the tree
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.
7.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. Each row is one customer: 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.
7.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 and no repeated rows, so nothing has to be filled or dropped (Topic 11). Two columns are text: country and gender.
7.3Step 3: drop what carries no information
df = df.drop(columns=["customer_id"])
print(df.shape)Output
(10000, 11)
An identification number is different for every customer and says nothing about him. A tree would even use it: it could find a threshold on the number that happens to separate a few customers in the training data, and learn noise (Topic 24).
7.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. So the accuracy alone will not judge the tree; the measures of Topic 28 will.
7.5Step 5: outliers
The upper limit of the IQR rule for age (Topic 25):
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 62. They are real customers, not mistakes, and a tree only asks whether an age is above a threshold, not how far above it lies (Part 6). They stay in the data.
7.6Step 6: encode
gender has two values and becomes 0 and 1. country has three values without an order and gets one-hot encoding (Topic 25). products_number stays a number: the tree can split it where it needs to (Part 6).
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']
Eleven features and the target, all numbers.
7.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, 2,000 for the test (Topic 23). The same random_state as in Topics 27 and 28 gives the same test customers, so the results can be compared.
7.8Step 8: no scaling
There is no scaling step. The tree will work with the features as they are: ages in years, balances in euros. Part 9 checks that scaling would change nothing.
Try it yourself
Show a hint
many = df[df["products_number"] > 2], then print(len(many)) and print(round(many["churn"].mean(), 4)). This is the group that a tree can cut off with the question "products > 2.5?".Show the solution
many = df[df["products_number"] > 2]
print(len(many))
print(round(many["churn"].mean(), 4))Output
326 0.8589
8The first tree
8.1Train and judge
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train, y_train)
print(tree.score(X_train, y_train))
print(round(tree.score(X_test, y_test), 4))Output
1.0 0.7845
Change it and run: write DecisionTreeClassifier(max_depth=4, random_state=42) and run: the training accuracy falls below 1 and the test accuracy rises.
A training accuracy of 1.0 and a test accuracy of 0.7845. The tree is right for every training customer and for only 78 of 100 new customers: it is lower than the baseline of always answering "stays" (0.8035, Topic 27). This is overfitting in its purest form.
8.2How big is it?
print(tree.get_depth())
print(tree.get_n_leaves())Output
24 1150
A depth of 24 and 1,150 leaves for 8,000 training customers: on average fewer than 7 customers per leaf. Many leaves hold a single customer. The tree has written down the training data, it has not learned rules.
8.3The measures of Topic 28
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score
predicted = tree.predict(X_test)
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))Output
[[1371 236] [ 195 198]] 0.4562 0.5038 0.4788
The recall, 0.5038, is better than that of logistic regression (0.3639 in Topic 28), but the precision is low: almost every second customer the tree marks as leaving stays.
leaving = tree.predict_proba(X_test)[:, 1]
print(sorted(set(leaving)))
print(round(roc_auc_score(y_test, leaving), 4))Output
[np.float64(0.0), np.float64(1.0)] 0.6785
Every leaf of this tree is pure, so the only probabilities it can give are 0 and 1. The ROC curve has a single point between its corners, and the AUC is only 0.6785, far below the 0.837 of logistic regression. A tree with pure leaves cannot rank its customers.
Try it yourself
max_depth=4 and random_state=42. Print its training accuracy and its test accuracy, each rounded to 4 decimals.Show a hint
model = DecisionTreeClassifier(max_depth=4, random_state=42), model.fit(X_train, y_train), then score on each part. Compare with the full tree: the training accuracy falls, the test accuracy rises.Show the solution
model = DecisionTreeClassifier(max_depth=4, random_state=42)
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 4))
print(round(model.score(X_test, y_test), 4))Output
0.8534 0.8535
9A tree you can read, and a tree that works
9.1A small tree
small = DecisionTreeClassifier(max_depth=3, random_state=42)
small.fit(X_train, y_train)
print(round(small.score(X_train, y_train), 4))
print(round(small.score(X_test, y_test), 4))Output
0.8455 0.8485
Change it and run: change max_depth=3 to max_depth=2 and run.
Only three questions on every path, and the test accuracy rises from 0.7845 to 0.8485. Training and test accuracy are now almost equal: the tree no longer learns noise.
9.2Its rules as text
export_text writes the tree as rules. show_weights=True adds, for every leaf, how many training customers of each class ended there:
from sklearn.tree import export_text
print(export_text(small, feature_names=list(X.columns), show_weights=True))Output
|--- age <= 44.50 | |--- products_number <= 2.50 | | |--- products_number <= 1.50 | | | |--- weights: [2410.00, 542.00] class: 0 | | |--- products_number > 1.50 | | | |--- weights: [2886.00, 149.00] class: 0 | |--- products_number > 2.50 | | |--- balance <= 57003.37 | | | |--- weights: [22.00, 34.00] class: 1 | | |--- balance > 57003.37 | | | |--- weights: [6.00, 81.00] class: 1 |--- age > 44.50 | |--- active_member <= 0.50 | | |--- age <= 51.50 | | | |--- weights: [226.00, 276.00] class: 1 | | |--- age > 51.50 | | | |--- weights: [37.00, 265.00] class: 1 | |--- active_member > 0.50 | | |--- products_number <= 2.50 | | | |--- weights: [765.00, 250.00] class: 0 | | |--- products_number > 2.50 | | | |--- weights: [4.00, 47.00] class: 1
How to read it:
- Every line with
<=or>is a question; the deeper the indentation, the deeper the node. - The root question is
age <= 44.50: the tree found that the age separates leaving and staying customers best, as the hand example of Part 3 did with its ten customers. - For the younger customers the next question is about
products_number: customers with more than 2 products leave far more often. For the older customers it isactive_member. weights: [a, b]are the training customers of the leaf who stayed (a) and who left (b). The class is the larger of the two, andpredict_probais .
The root and the second level tell the story of the data in three lines: the age, the number of products and the activity of a customer decide most of the churn. It is the same story the weights of logistic regression told in Topic 27, now as rules.
9.3The tree as a picture
import matplotlib.pyplot as plt
from sklearn.tree import plot_tree
plt.figure(figsize=(16, 7))
plot_tree(small, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True, fontsize=9)
plt.show()
plot_tree draws the same tree. Every box shows its question, its Gini impurity, its number of training customers (samples), the customers of each class (value) and its class. filled=True colours a box by its class: the stronger the colour, the purer the node.
9.4Following one customer
customer = X_test.iloc[[0]]
print(customer[["age", "products_number", "active_member", "balance"]])
print(small.predict(customer))
print(small.predict_proba(customer).round(3))Output
age products_number active_member balance 6252 32 2 0 96709.07 [0] [[0.951 0.049]]
Change it and run: change iloc[[0]] to iloc[[1]] and follow the second test customer through the rules.
X_test.iloc[[0]] is the first test customer, kept as a table of one row (two brackets). Follow him through the rules above: he is 32, so age <= 44.50 sends him left; he has 2 products, so products_number <= 2.50 and then products_number > 1.50. He lands in the leaf with weights: [2886.00, 149.00]: 149 of its 3,035 training customers left.
That is the second number of predict_proba, and because it is below 0.5 the tree predicts 0: he stays. Every other test customer in the same leaf gets exactly the same probability.
9.5Which features did the tree use?
importances = pd.Series(small.feature_importances_, index=X.columns)
print(importances.sort_values(ascending=False).round(3))Output
age 0.463 products_number 0.326 active_member 0.201 balance 0.010 credit_score 0.000 gender 0.000 tenure 0.000 credit_card 0.000 estimated_salary 0.000 country_Germany 0.000 country_Spain 0.000 dtype: float64
feature_importances_ adds up, for every feature, how much its splits lowered the impurity, weighted by the number of rows they split, and scales the sums to add up to 1. The small tree uses only a few features; the rest have importance 0. A feature with importance 0 was not useless in general, it was simply never chosen.
Try it yourself
small predicts for him, then his probabilities rounded to 3 decimals.Show a hint
second = X_test.iloc[[1]], then print(small.predict(second)) and print(small.predict_proba(second).round(3)). Follow him through the rules to see his leaf.Show the solution
second = X_test.iloc[[1]]
print(small.predict(second))
print(small.predict_proba(second).round(3))Output
[0] [[0.951 0.049]]
10Tuning the tree
10.1max_depth: from underfitting to overfitting
for depth in [1, 2, 3, 4, 5, 6, 8, 10, 15, None]:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
model.fit(X_train, y_train)
print(depth, round(model.score(X_train, y_train), 4), round(model.score(X_test, y_test), 4))Output
1 0.7945 0.8035 2 0.8401 0.844 3 0.8455 0.8485 4 0.8534 0.8535 5 0.8589 0.8575 6 0.8661 0.86 8 0.8819 0.8565 10 0.9011 0.842 15 0.9699 0.805 None 1.0 0.7845
Every line shows the depth, the training accuracy and the test accuracy.
- The training accuracy rises with every level, up to 1.0 for the unlimited tree (
None). - The test accuracy rises at first, is highest around the depths 5 and 6, and then falls again, down to 0.7845 for the unlimited tree.
depths = list(range(1, 16))
train_scores = []
test_scores = []
for depth in depths:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
model.fit(X_train, y_train)
train_scores.append(model.score(X_train, y_train))
test_scores.append(model.score(X_test, y_test))
plt.plot(depths, train_scores, marker="o", label="training data")
plt.plot(depths, test_scores, marker="o", label="test data")
plt.xlabel("max_depth")
plt.ylabel("accuracy")
plt.title("Accuracy of a tree against its depth")
plt.legend()
plt.show()
Move max_depth and watch the bank tree. The last step of the slider, 16, stands for no limit at all.
max_depth=5: a tree of depth 5 with 32 leaves. Training accuracy 0.8589, test accuracy 0.8575.
Orange: training data, teal: test data. Small depths underfit, large depths overfit; the gap between the curves is the overfitting.
This is the picture of Topic 23 again: on the left the tree is too simple (underfitting: both accuracies low), on the right it is too complex (overfitting: the curves drift apart). The best depth lies in between.
10.2Choosing the depth with cross-validation
The test data may not choose the depth (Topic 23). Cross-validation on the training data does. Because the classes are unbalanced, the folds are judged here with the AUC of Topic 28: scoring="roc_auc" tells cross_val_score which measure to use.
from sklearn.model_selection import cross_val_score
for depth in [3, 4, 5, 6, 7, 8]:
model = DecisionTreeClassifier(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
3 0.7892 4 0.8144 5 0.8302 6 0.829 7 0.8276 8 0.8161
Change it and run: add scoring="f1" in the place of "roc_auc" and run: the F1-score may prefer another depth.
The mean AUC over the five folds is highest for a depth of 5. That is the choice. (Without scoring, cross_val_score uses the accuracy; other names are "f1", "recall" and "precision".)
10.3min_samples_leaf: large leaves
A second way to stop a tree: every leaf must keep a number of customers.
for leaf in [1, 10, 20, 50, 100]:
model = DecisionTreeClassifier(min_samples_leaf=leaf, random_state=42)
model.fit(X_train, y_train)
leaving = model.predict_proba(X_test)[:, 1]
print(leaf, model.get_n_leaves(), round(roc_auc_score(y_test, leaving), 4))Output
1 1150 0.6785 10 395 0.8023 20 241 0.8284 50 109 0.843 100 60 0.8354
Every line shows min_samples_leaf, the number of leaves and the test AUC. With leaves of at least 50 customers the tree has about a hundred leaves instead of 1,150, and its AUC rises from 0.68 to 0.84: larger leaves give reliable shares, and reliable shares rank the customers well.
10.4criterion: Gini or entropy
for criterion in ["gini", "entropy"]:
model = DecisionTreeClassifier(max_depth=5, criterion=criterion, random_state=42)
model.fit(X_train, y_train)
print(criterion, round(model.score(X_test, y_test), 4))Output
gini 0.8575 entropy 0.857
The two measures give almost the same tree, as Part 3 said.
10.5ccp_alpha: pruning after growing
for alpha in [0.0, 0.0005, 0.001, 0.002, 0.005]:
model = DecisionTreeClassifier(ccp_alpha=alpha, random_state=42)
model.fit(X_train, y_train)
print(alpha, model.get_n_leaves(), round(model.score(X_test, y_test), 4))Output
0.0 1150 0.7845 0.0005 36 0.864 0.001 22 0.8595 0.002 12 0.857 0.005 7 0.8485
Every line shows ccp_alpha, the number of leaves and the test accuracy. The tree is grown in full and then cut back. Already a small ccp_alpha removes most of the 1,150 leaves, and the test accuracy rises from 0.78 to about 0.86. Too large a value cuts too much, and the accuracy falls again.
10.6The tuned tree
final = DecisionTreeClassifier(max_depth=5, random_state=42)
final.fit(X_train, y_train)
predicted = final.predict(X_test)
leaving = final.predict_proba(X_test)[:, 1]
print(confusion_matrix(y_test, predicted))
print(round(final.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
[[1559 48] [ 237 156]] 0.8575 0.7647 0.3969 0.5226 0.8328
Change it and run: change max_depth=5 to max_depth=6 and run.
The confusion matrix, the accuracy, the precision, the recall, the F1-score and the AUC of the tuned tree, on the same 2,000 test customers as in Topic 28:
| Measure | Logistic regression (Topic 28) | Full tree | Tree with max_depth=5 |
|---|---|---|---|
| Accuracy | 0.843 | 0.7845 | 0.8575 |
| Precision | 0.6908 | 0.4562 | 0.7647 |
| Recall | 0.3639 | 0.5038 | 0.3969 |
| F1-score | 0.4767 | 0.4788 | 0.5226 |
| AUC | 0.837 | 0.6785 | 0.8328 |
Accuracy
Precision
Recall
F1-score
AUC
The tuned tree beats logistic regression on the accuracy, the precision and the F1-score, and reaches almost the same AUC, with eleven features as they are: no scaling and no one-hot encoding of products_number. The full tree loses on almost every measure. The same model can be the worst or the best of the three: the hyperparameters decide.
10.7More recall: class_weight
For the bank a missed customer is the expensive mistake (Topic 28). The tuned tree finds only about 40 of 100 leaving customers.
balanced = DecisionTreeClassifier(max_depth=5, class_weight="balanced", random_state=42)
balanced.fit(X_train, y_train)
predicted_balanced = balanced.predict(X_test)
print(confusion_matrix(y_test, predicted_balanced))
print(round(recall_score(y_test, predicted_balanced), 4))
print(round(precision_score(y_test, predicted_balanced), 4))Output
[[1152 455] [ 70 323]] 0.8219 0.4152
The recall roughly doubles, and the precision falls: more customers are found, at the price of more false alarms, exactly as with logistic regression in Topic 28.
10.8The importances of the tuned tree
importances = pd.Series(final.feature_importances_, index=X.columns)
importances.sort_values().plot(kind="barh")
plt.title("Feature importances of the tuned tree")
plt.xlabel("importance")
plt.show()
The age and the number of products carry most of the tree (0.431 and 0.334 of the importance), followed by the activity (0.155). Germany, the balance and the salary add a little; the gender, the credit score, the credit card and Spain are not used at all by this tree.
10.9Seeing a large tree
The tuned tree has 5 levels and 32 leaves: too many to read at once. Both tools can show only its top. max_depth inside export_text (and inside plot_tree) limits the drawing, not the model:
print(final.get_depth(), final.get_n_leaves())
print(export_text(final, feature_names=list(X.columns), max_depth=2))Output
5 32 |--- age <= 44.50 | |--- products_number <= 2.50 | | |--- products_number <= 1.50 | | | |--- truncated branch of depth 3 | | |--- products_number > 1.50 | | | |--- truncated branch of depth 3 | |--- products_number > 2.50 | | |--- balance <= 57003.37 | | | |--- truncated branch of depth 3 | | |--- balance > 57003.37 | | | |--- truncated branch of depth 3 |--- age > 44.50 | |--- active_member <= 0.50 | | |--- age <= 51.50 | | | |--- truncated branch of depth 3 | | |--- age > 51.50 | | | |--- truncated branch of depth 3 | |--- active_member > 0.50 | | |--- products_number <= 2.50 | | | |--- truncated branch of depth 3 | | |--- products_number > 2.50 | | | |--- truncated branch of depth 3
The first line gives the real size of the tree. In the rules, truncated branch of depth 3 marks a branch that goes on below the shown levels.
plt.figure(figsize=(16, 7))
plot_tree(final, max_depth=2, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True, fontsize=9)
plt.show()
The boxes with (...) below them continue further down. The top of the tuned tree asks the same first questions as the small tree: the age, then the number of products and the activity.
10.10Scaling changes nothing: the proof
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
scaled_tree = DecisionTreeClassifier(max_depth=5, random_state=42)
scaled_tree.fit(X_train_scaled, y_train)
print((scaled_tree.predict(X_test_scaled) == final.predict(X_test)).all())Output
True
True: on scaled features the tree gives exactly the same prediction for every one of the 2,000 test customers. Only the thresholds in its questions are different numbers.
Try it yourself
min_samples_leaf=50 and random_state=42. Print its number of leaves, its test accuracy and its test AUC, the last two rounded to 4 decimals.Show a hint
model = DecisionTreeClassifier(min_samples_leaf=50, random_state=42), fit, then model.get_n_leaves(), model.score(X_test, y_test) and roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]).Show the solution
model = DecisionTreeClassifier(min_samples_leaf=50, random_state=42)
model.fit(X_train, y_train)
print(model.get_n_leaves())
print(round(model.score(X_test, y_test), 4))
print(round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4))Output
109 0.8505 0.843
Try it yourself
predicted), then the F1-score of the balanced tree (predicted_balanced), each rounded to 4 decimals. Which is higher?Show a hint
f1_score(y_test, predicted) and f1_score(y_test, predicted_balanced). The balanced tree finds many more leaving customers.Show the solution
print(round(f1_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted_balanced), 4))Output
0.5226 0.5517
11The 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: mistake or real | 359 older customers: real, kept; a tree does not mind them |
| 6. Encode | text to numbers | gender 0 and 1, country one-hot; products_number stays a number |
| 7. Split | training and test data | 8,000 and 2,000 |
| 8. Scale | only for models that need it | not for a tree |
| 9. First model | a simple start | the full tree: overfits (test accuracy 0.7845) |
| 10. Tune | hyperparameters with cross-validation | max_depth=5, chosen by the AUC of 5 folds |
| 11. Judge | the measures of Topic 28 on the test data | accuracy 0.8575, F1 0.5226, AUC 0.8328 |
| 12. Explain | the rules and the feature importances | age, number of products, activity |
Compared with Topics 27 and 28, scaling has dropped out, the one-hot encoding of products_number is not needed, and a new step has come in: reading and explaining the model itself.
Try it yourself
max_depth chosen? (d) Which measures judge the tuned tree?Show a hint
Show the solution
Answer: (a) scaling; (b) explaining the model; (c) the training data, with cross-validation; (d) the measures of Topic 28.
A tree does not need scaling. Its rules and importances explain it, which is a step of its own. The depth is a hyperparameter, chosen without the test data; the finished tree is judged with the confusion matrix, precision, recall, F1 and AUC.
12Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Training a tree without any limit and reporting the training accuracy. | A full tree is always right on its training data: 1.0 says nothing. | Judge on the test data; limit the tree. |
Choosing max_depth with the test data. | The test data then takes part in building the model. | Cross-validation on the training data. |
| Scaling the features "because the workflow says so". | It changes nothing for a tree. | Scale only for models that need it (Part 6). |
Leaving text columns in X. | scikit-learn's trees accept only numbers: an error. | Encode gender and country first. |
Keeping customer_id as a feature. | A tree can split on it and learn noise. | Drop identification numbers. |
Reading feature_importances_ as "how a feature changes the probability". | It says how much a feature lowered the impurity, not in which direction it pushes. | Read the rules for the direction. |
| Thinking a feature with importance 0 is useless. | It was only never chosen; a similar feature may have taken its place. | Treat importance as "used by this tree". |
| Trusting the probabilities of a deep tree. | Pure leaves give only 0 and 1: the AUC collapses. | Limit the depth, or use min_samples_leaf. |
| Expecting the same tree after a small change of the data. | A tree is unstable: a different first split changes everything below it. | Random forests (Topic 30) average many trees. |
Forgetting random_state. | Ties between features are broken at random: the tree can differ between runs. | Fix random_state. |
| Thinking a tree finds the best tree overall. | It is greedy: the best question now, one node at a time. | It is a good heuristic, not a guarantee. |
| Expecting a regression tree to predict beyond the training values. | A leaf is a mean of training targets. | Know the range of its predictions. |
13Solved problems
Sixteen problems. The first four 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: Gini and entropy of a node
A node holds 10 customers: 3 left and 7 stayed. Calculate its Gini impurity and its entropy. Use and .
Idea. ; the formulas of Part 3.
Why: both numbers are clearly above 0 and below their highest values (0.5 and 1): the node is mixed, but not half and half.
Problem 2: Choosing between two questions
A node holds 10 customers, 4 of them left. Question A splits it into 5 customers (4 left) and 5 customers (0 left). Question B splits it into 6 customers (3 left) and 4 customers (1 left). Which question does the tree choose?
Idea. The Gini of each group, then the mean weighted with the group sizes; the lowest wins (Part 3).
Question A:
Question B:
Why: question A leaves a pure group and an almost pure one: 0.16 against 0.45. The tree chooses A.
Problem 3: Thresholds of a numerical column
Four customers have the ages 22, 30, 41 and 48; the first two stayed, the last two left. Which thresholds does the tree try for age, and which one does it choose?
Idea. The thresholds lie half way between neighbouring values (Part 3).
Why: "age > 35.5?" puts the two customers who stayed on one side and the two who left on the other: two pure groups, Gini 0 after the split. The other two thresholds leave a mixed group.
Problem 4: The answer of a leaf
A leaf of a trained tree holds 40 training customers, 10 of whom left. What does predict_proba give for a new customer in this leaf, and what does predict give? Which class would the threshold 0.2 give?
Idea. A leaf answers with the shares of its training rows (Part 2) and the threshold of Topic 27.
Why: 0.25 is below 0.5, so predict says 0 (stays). With the threshold 0.2 the same customer would be marked as leaving, because 0.25 is at least 0.2.
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 7).
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 has to be filled, and one customer in five left: the accuracy will not be enough.
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 a tree (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: 12 columns: eleven features and the target.
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 anything learns from the rows. No scaling follows: a tree does not need it.
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 tree without limits
Train a DecisionTreeClassifier with random_state=42. Print its training accuracy, its test accuracy (rounded to 4 decimals) and its number of leaves.
Idea. The full tree of Part 8.
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train, y_train)
print(tree.score(X_train, y_train))
print(round(tree.score(X_test, y_test), 4))
print(tree.get_n_leaves())Output
1.0 0.7944 1082
Why: perfect on the training data, below the baseline on the test data, and about a thousand leaves: overfitting.
Problem 9: The rules of a small tree
Train a tree with max_depth=2 and random_state=42 and print its rules with export_text.
Idea. A shallow tree can be read as rules (Part 9).
from sklearn.tree import export_text
small = DecisionTreeClassifier(max_depth=2, random_state=42)
small.fit(X_train, y_train)
print(export_text(small, feature_names=list(X.columns)))Output
|--- age <= 42.50 | |--- products_number <= 2.50 | | |--- class: 0 | |--- products_number > 2.50 | | |--- class: 1 |--- age > 42.50 | |--- active_member <= 0.50 | | |--- class: 1 | |--- active_member > 0.50 | | |--- class: 0
Why: with another split of the data the first question is again about the age, and the second about the number of products and the activity: the story of the data does not depend on the split.
Problem 10: Depth against accuracy
For the depths 2, 4, 6, 8 and 10, print the depth, the training accuracy and the test accuracy, rounded to 4 decimals.
Idea. One hyperparameter changed at a time (Part 10).
for depth in [2, 4, 6, 8, 10]:
model = DecisionTreeClassifier(max_depth=depth, random_state=42)
model.fit(X_train, y_train)
print(depth, round(model.score(X_train, y_train), 4), round(model.score(X_test, y_test), 4))Output
2 0.8308 0.8252 4 0.852 0.8448 6 0.8641 0.8508 8 0.8813 0.8468 10 0.9024 0.8352
Why: the training accuracy keeps rising, the test accuracy rises and then falls: from underfitting to overfitting.
Problem 11: Choosing the depth
Compare the depths 4, 5, 6 and 7 with a 5-fold cross-validation on the training data, judged by the AUC. Print each depth with its mean AUC, rounded to 4 decimals.
Idea. cross_val_score with scoring="roc_auc" (Part 10).
from sklearn.model_selection import cross_val_score
for depth in [4, 5, 6, 7]:
model = DecisionTreeClassifier(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
4 0.8112 5 0.8277 6 0.8271 7 0.8155
Why: the depth with the highest mean AUC is chosen, without looking at the test data.
Problem 12: The tuned tree
Train the tree with max_depth=5 and random_state=42, call it final, and print the confusion matrix of its test predictions.
Idea. The chosen depth, judged once on the test data (Part 10).
from sklearn.metrics import confusion_matrix
final = DecisionTreeClassifier(max_depth=5, random_state=42)
final.fit(X_train, y_train)
predicted = final.predict(X_test)
print(confusion_matrix(y_test, predicted))Output
[[1888 102] [ 283 227]]
Why: read it like a text: TN, FP, FN, TP. The tree finds a part of the leaving customers and gives few false alarms.
Problem 13: Its measures
Print the precision, the recall, the F1-score and the AUC of final, each rounded to 4 decimals.
Idea. The measures of Topic 28; the AUC needs the probabilities.
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score
leaving = final.predict_proba(X_test)[:, 1]
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
0.69 0.4451 0.5411 0.839
Why: a fair precision and a modest recall, and an AUC far above that of a full tree, whose probabilities are only 0 and 1 (Part 8).
Problem 14: Balanced classes
Train the same tree with class_weight="balanced". Print its recall and its precision, rounded to 4 decimals.
Idea. More weight for the rare class (Part 5).
balanced = DecisionTreeClassifier(max_depth=5, 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))Output
0.7627 0.4346
Why: the recall rises strongly and the precision falls: the bank finds more of the customers who leave and calls more who would have stayed.
Problem 15: Feature importances
Print the three most important features of final with their importances, rounded to 3 decimals.
Idea. feature_importances_ as a Series, sorted (Part 9).
importances = pd.Series(final.feature_importances_, index=X.columns)
print(importances.sort_values(ascending=False).head(3).round(3))Output
age 0.468 products_number 0.321 active_member 0.156 dtype: float64
Why: the age and the number of products lead again: the tree explains itself in the same words as in the lesson.
Problem 16: Draw the small tree
Draw the tree small of Problem 9 with plot_tree, with the names of the features and of the classes.
Idea. The picture of the rules (Part 9).
import matplotlib.pyplot as plt
from sklearn.tree import plot_tree
plt.figure(figsize=(12, 6))
plot_tree(small, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True, fontsize=10)
plt.show()
Why: three questions and four leaves, each with its Gini impurity, its customers and its class: a model a bank manager can read.
14Practice
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 a tuned tree. Under every problem there is a hint and a solution.
14.1Group A: by hand
- 1.A node holds 8 customers: 2 left and 6 stayed. Calculate (a) its Gini impurity, (b) its entropy, with 3 decimals. Use and .
Show a hint
. Gini is .Show one possible solution
Answer: (a) 0.375; (b) 0.811.
- 2.A node of 10 customers (5 left) can be split by question A into 4 customers (4 left) and 6 customers (1 left), or by question B into 5 customers (3 left) and 5 customers (2 left). Calculate the Gini after each split, with 3 decimals, and say which question the tree chooses.
Show a hint
For each group , then weight with 0.4 and 0.6, or with 0.5 and 0.5.Show one possible solution
Answer: A: 0.167; B: 0.48; the tree chooses A.
Question A: the first group is pure (0); the second has .
Question B: both groups have or .
A is lower, so the tree chooses A.
- 3.A tree has the rules: age and products : stays; age and products : leaves; age and not active: leaves; age and active: stays. Predict for (a) a customer of 38 with 3 products, (b) a customer of 50 who is active, (c) a customer of 60 who is not active.
Show a hint
Start at the root question about the age, then follow one branch.Show one possible solution
Answer: (a) leaves; (b) stays; (c) leaves.
(a) 38 is at most 44.5, and 3 products is more than 2.5: leaves. (b) 50 is above 44.5, active: stays. (c) 60 is above 44.5, not active: leaves.
- 4.(a) A full tree has a training accuracy of 1.0 and a test accuracy of 0.78. What is the problem? (b) Does a larger
min_samples_leafmake the tree simpler or more complex? (c) Does a tree need scaled features?Show a hint
Compare the two accuracies. Think of what a leaf with at least 50 customers can no longer do.Show one possible solution
Answer: (a) overfitting; (b) simpler; (c) no.
(a) Perfect on the training data and much worse on new data: the tree learned the training rows by heart. (b) Every leaf must keep more customers, so there are fewer, larger leaves. (c) A split depends only on the order of the values, and scaling keeps the order.
14.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 tree
Read the file, drop and encode, split. No scaling: a tree does not need it.
- 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 men. 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 number of men is the sum of the column.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"].sum())Output
5457
- 7.One-hot encode
countryinside the table, withdrop_first=Trueanddtype=int. Print the names of the columns as a list. This step continues from Step 6.Show a hint
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int), thenprint(df.columns.tolist()).products_numberstays a number.Show one possible solution
Python, continues from the cells abovedf = 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']
- 8.Make
X(all columns withoutchurn) andy(churn). Split them withtest_size=0.3andrandom_state=1. Print the shapes ofX_trainandX_teston one line. This step continues from Step 7.Show a hint
X = df.drop(columns=["churn"]),y = df["churn"], thenX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)andprint(X_train.shape, X_test.shape).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(X_train.shape, X_test.shape)Output
(7000, 11) (3000, 11)
Steps 9 to 12: the full tree, a small tree, the best depth
A tree without limits, its size, a tree of depth 3, and the depth chosen by cross-validation.
- 9.Train a
DecisionTreeClassifiercalledtreewithrandom_state=42. Print its training accuracy, then its test accuracy rounded to 4 decimals. This step continues from Step 8.Show a hint
tree = DecisionTreeClassifier(random_state=42),tree.fit(X_train, y_train), thenprint(tree.score(X_train, y_train))andprint(round(tree.score(X_test, y_test), 4)).Show one possible solution
Python, continues from the cells abovefrom sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(random_state=42) tree.fit(X_train, y_train) print(tree.score(X_train, y_train)) print(round(tree.score(X_test, y_test), 4))Output
1.0 0.7927
- 10.Print the depth of
tree, then its number of leaves. This step continues from Step 9.Show a hint
print(tree.get_depth())andprint(tree.get_n_leaves()).Show one possible solution
Python, continues from the cells aboveprint(tree.get_depth()) print(tree.get_n_leaves())Output
23 1006
- 11.Train a tree with
max_depth=3andrandom_state=42. Print its training accuracy and its test accuracy, each rounded to 4 decimals. This step continues from Step 9.Show a hint
small = DecisionTreeClassifier(max_depth=3, random_state=42),small.fit(X_train, y_train), thenscoreon each part.Show one possible solution
Python, continues from the cells abovesmall = DecisionTreeClassifier(max_depth=3, random_state=42) small.fit(X_train, y_train) print(round(small.score(X_train, y_train), 4)) print(round(small.score(X_test, y_test), 4))Output
0.8401 0.8393
- 12.For the depths 4, 5 and 6, print the depth and the mean AUC of a 5-fold cross-validation on the training data, rounded to 4 decimals. This step continues from Step 9.
Show a hint
In a loop:model = DecisionTreeClassifier(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)).Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import cross_val_score for depth in [4, 5, 6]: model = DecisionTreeClassifier(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
4 0.8136 5 0.8313 6 0.8263
Steps 13 to 16: the tuned tree, its measures and its picture
The confusion matrix, recall, F1 and AUC, the most important feature, and a tree drawn with plot_tree.
- 13.Train the tree with
max_depth=5andrandom_state=42, calledfinal, and put its test predictions intopredicted. Print the confusion matrix. This step continues from Step 9.Show a hint
final.fit(X_train, y_train),predicted = final.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 final = DecisionTreeClassifier(max_depth=5, random_state=42) final.fit(X_train, y_train) predicted = final.predict(X_test) print(confusion_matrix(y_test, predicted))Output
[[2332 41] [ 398 229]]
- 14.Print the recall, the F1-score and the AUC of
final, in this order, each rounded to 4 decimals. This step continues from Step 13.Show a hint
recall_scoreandf1_scorewith(y_test, predicted);roc_auc_scorewith the probabilitiesfinal.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 leaving = final.predict_proba(X_test)[:, 1] 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
0.3652 0.5106 0.8442
- 15.Print the name of the most important feature of
final, then its importance rounded to 3 decimals. This step continues from Step 13.Show a hint
importances = pd.Series(final.feature_importances_, index=X.columns), thenprint(importances.idxmax())andprint(round(importances.max(), 3)).Show one possible solution
Python, continues from the cells aboveimportances = pd.Series(final.feature_importances_, index=X.columns) print(importances.idxmax()) print(round(importances.max(), 3))Output
age 0.415
- 16.Train a tree with
max_depth=2andrandom_state=42. Print its test accuracy rounded to 4 decimals, then draw it withplot_tree, with the names of the features and of the classes. This step continues from Step 9.Show a hint
two = DecisionTreeClassifier(max_depth=2, random_state=42),fit,print(round(two.score(X_test, y_test), 4)), thenplot_tree(two, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True)andplt.show().Show one possible solution
Python, continues from the cells aboveimport matplotlib.pyplot as plt from sklearn.tree import plot_tree two = DecisionTreeClassifier(max_depth=2, random_state=42) two.fit(X_train, y_train) print(round(two.score(X_test, y_test), 4)) plt.figure(figsize=(12, 6)) plot_tree(two, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True, fontsize=10) plt.show()Output
0.8257

15Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
16Summary
| Formula | Meaning | |
|---|---|---|
| Gini impurity | 0 for a pure node, 0.5 for a half-and-half node | |
| Entropy | 0 for a pure node, 1 for a half-and-half node | |
| A split | the lowest value wins | |
| Information gain | the largest gain wins | |
| Leaf of a classification tree | the share of each class | predict_proba; predict takes the larger share |
| Leaf of a regression tree | the mean of the target | a step function |
| Code | What it does |
|---|---|
DecisionTreeClassifier(random_state=42) | a classification tree without limits |
DecisionTreeClassifier(max_depth=5) | a tree of at most 5 questions on every path |
min_samples_leaf, max_leaf_nodes, ccp_alpha | other ways to keep a tree small |
criterion="entropy" | entropy in the place of Gini |
class_weight="balanced" | more weight for the rare class |
tree.get_depth(), tree.get_n_leaves() | the size of the tree |
export_text(tree, feature_names=list(X.columns)) | the rules as text |
plot_tree(tree, feature_names=..., class_names=..., filled=True) | the tree as a picture |
tree.feature_importances_ | how much each feature was used |
cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc") | choose a hyperparameter by the AUC |
DecisionTreeRegressor | the regression tree |
Rules to keep
- A tree predicts with a row of yes-or-no questions; each compares one feature with one threshold.
- It chooses each question greedily: the split with the lowest weighted impurity (Gini or entropy).
- Without limits it overfits: training accuracy 1.0, poor test results, probabilities of only 0 and 1.
- Limit it with
max_depth,min_samples_leaforccp_alpha, chosen with cross-validation on the training data. - A tree needs no scaling and is robust to outliers in the features; text must still be encoded.
- Judge it with the measures of Topic 28, and explain it with its rules and its feature importances.
What comes next
A single tree is easy to read, but unstable: a few different training rows can change its first question and everything below it. Topic 30, random forests, trains hundreds of trees on different samples of the data and lets them vote: a model that is far more stable and usually more accurate, built from the tree of this lesson.