Asiman Data School

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.

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. 1.What a decision tree is, its parts, and the tasks it is used for
  2. 2.How a tree makes a decision for a new row
  3. 3.How a tree chooses its first question and every question after it: Gini impurity, entropy and information gain
  4. 4.How a numerical column is split, and how a regression tree works
  5. 5.Why a tree overfits, and the hyperparameters that stop it
  6. 6.What scaling, encoding, outliers and missing values mean for trees, and for the models still to come
  7. 7.A whole project with DecisionTreeClassifier: from the file to a tuned tree, its rules, its feature importances and its measures
The words of this lesson
WordMeaning
Decision treea model that predicts by asking a row of yes-or-no questions about the features
Nodeone question of the tree, or one end of it
Root nodethe first question, at the top; all training rows start there
Branchthe way from a question to the next node: "yes" or "no"
Internal nodea node with a question, between the root and the leaves
Leafa node without a question: here the tree gives its answer
Depththe number of questions on the longest way from the root to a leaf
Splitdividing the rows of a node into two groups with one question
Impurityhow mixed the classes in a node are: 0 when all rows have the same class
Gini impurityan impurity measure: the chance that two rows drawn at random from the node have different classes
Entropyanother impurity measure, from information theory
Information gainhow much a split lowers the impurity
Pruninglimiting or cutting back a tree so that it does not learn the noise
Feature importancehow 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

noyesnoyesnoyesroot nodeage > 44?internal nodemore than 2 products?internal nodeactive member?leafstaysleafleavesleafleavesleafstays
The parts of a decision tree. The root node holds the first question, the internal nodes hold later questions, and the leaves (grey) hold the answers. Every way from the root to a leaf passes two questions: the depth of this tree is 2.
  • 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 and regression
Classification treeRegression tree
The targeta class: leaves or stays, spam or nota number: a price, a balance, a mark
A leaf answers withthe most common class of its rows (and their shares as probabilities)the mean of the target of its rows
A split is chosen bythe impurity of the classes (Gini, entropy)the squared error
scikit-learnDecisionTreeClassifierDecisionTreeRegressor

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 and weaknesses
StrengthsWeaknesses
Easy to explain: every prediction is a short row of rulesA 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 orderIts 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 predictIts probabilities are coarse: the shares of a few leaves

Try it yourself

Look at the tree in the picture above. (a) How many questions does the way from the root to any leaf pass? (b) Which node holds the first question? (c) What does a leaf hold? (d) A tree predicts a price. Is it a classification tree or a regression tree?

Show a hint
Count the levels below the root. A leaf has no question.
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:

  1. Root: is the age above 44? 52 is above 44: yes, go right.
  2. Next question: is he an active member? No, go left.
  3. A leaf: leaves.

A second customer, 30 years old with 1 product:

  1. Is the age above 44? No, go left.
  2. More than 2 products? No, go left.
  3. 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:

probability of leaving=260400=0.65\text{probability of leaving} = \frac{260}{400} = 0.65

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

Use the tree of Part 1. (a) What does it predict for a customer of 60 who is an active member? (b) For a customer of 35 with 3 products? (c) A leaf received 50 training customers, and 20 of them left. What probability of leaving does a new customer in this leaf get? (d) Which class does predict give him?

Show a hint
Start at the root: is the age above 44? Then follow one branch. In a leaf, the probability is the share of the customers who left.
Show the solution

Answer: (a) stays; (b) leaves; (c) 0.4; (d) stays.

2050=0.4\frac{20}{50} = 0.4

(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 pp of the rows belongs to class 1 and 1−p1 - p to class 0:

Gini=1−p2−(1−p)2\text{Gini} = 1 - p^2 - (1 - p)^2

It is the chance that two rows, drawn at random from the node, have different classes.

  • A pure node (p=0p = 0 or p=1p = 1): Gini=0\text{Gini} = 0.
  • The most mixed node, half and half (p=0.5p = 0.5): Gini=1−0.25−0.25=0.5\text{Gini} = 1 - 0.25 - 0.25 = 0.5, the largest value for two classes.

3.3Entropy

entropy=−plog⁡2p−(1−p)log⁡2(1−p)\text{entropy} = -p \log_2 p - (1 - p) \log_2 (1 - p)

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).

00.5100.250.50.751
  • Gini impurity
  • entropy
The two impurity measures against the share p of class 1 in a node. Both are 0 for a pure node (p = 0 or p = 1) and largest for a half-and-half node: the Gini impurity at 0.5, the entropy at 1. They have the same shape, so they almost always choose the same questions.

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:

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

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:

information gain=entropy before−entropy after\begin{aligned} & \text{information gain} \\[4pt] &= \text{entropy before} - \text{entropy after} \end{aligned}

3.5A worked example: ten customers

Ten customers of a bank. For each we know three yes-or-no facts and whether he left:

A worked example: ten customers
CustomerOver 50Active memberTwo or more productsLeft
Ayesnonoyes
Byesnonoyes
Cyesnoyesyes
Dyesyesyesno
Enoyesnoyes
Fnoyesnono
Gnoyesyesno
Hnoyesnono
Inonoyesno
Jnononono

4 of the 10 customers left, 6 stayed.

Step 1: the impurity of the root. All ten customers are in the root, and p=0.4p = 0.4:

Gini(root)=1−0.42−0.62=1−0.16−0.36=0.48\begin{aligned} \text{Gini(root)} &= 1 - 0.4^2 - 0.6^2 \\[4pt] &= 1 - 0.16 - 0.36 = 0.48 \end{aligned}

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).

Gini(yes)=1−0.752−0.252=1−0.5625−0.0625=0.375Gini(no)=1−(16)2−(56)2=1−0.028−0.694=0.278after the split=0.4×0.375+0.6×0.278=0.150+0.167=0.317\begin{aligned} \text{Gini(yes)} &= 1 - 0.75^2 - 0.25^2 \\[4pt] &= 1 - 0.5625 - 0.0625 = 0.375 \\[8pt] \text{Gini(no)} &= 1 - \left(\tfrac{1}{6}\right)^2 - \left(\tfrac{5}{6}\right)^2 \\[4pt] &= 1 - 0.028 - 0.694 = 0.278 \\[8pt] \text{after the split} &= 0.4 \times 0.375 + 0.6 \times 0.278 \\[4pt] &= 0.150 + 0.167 = 0.317 \end{aligned}

Question "Active member?": yes = D, E, F, G, H (1 left of 5); no = A, B, C, I, J (3 left of 5).

Gini(yes)=1−0.22−0.82=1−0.04−0.64=0.32Gini(no)=1−0.62−0.42=1−0.36−0.16=0.48after the split=0.5×0.32+0.5×0.48=0.16+0.24=0.40\begin{aligned} \text{Gini(yes)} &= 1 - 0.2^2 - 0.8^2 \\[4pt] &= 1 - 0.04 - 0.64 = 0.32 \\[8pt] \text{Gini(no)} &= 1 - 0.6^2 - 0.4^2 \\[4pt] &= 1 - 0.36 - 0.16 = 0.48 \\[8pt] \text{after the split} &= 0.5 \times 0.32 + 0.5 \times 0.48 \\[4pt] &= 0.16 + 0.24 = 0.40 \end{aligned}

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).

Gini(yes)=1−0.252−0.752=0.375Gini(no)=1−0.52−0.52=0.5after the split=0.4×0.375+0.6×0.5=0.15+0.30=0.45\begin{aligned} \text{Gini(yes)} &= 1 - 0.25^2 - 0.75^2 = 0.375 \\[8pt] \text{Gini(no)} &= 1 - 0.5^2 - 0.5^2 = 0.5 \\[8pt] \text{after the split} &= 0.4 \times 0.375 + 0.6 \times 0.5 \\[4pt] &= 0.15 + 0.30 = 0.45 \end{aligned}

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.

A worked example: ten customers
QuestionGini after the splitDrop from 0.48
Over 50?0.3170.163
Active member?0.400.08
Two or more products?0.450.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).
noyesnoyesOver 50?10 customers, 4 leftGini 0.48stays6 customers, 1 leftGini 0.278Active member?4 customers, 3 leftGini 0.375leaves3 of 3 leftstays1 of 1 stayed
The finished tree of the ten customers. The root question "Over 50?" lowers the Gini impurity from 0.48 to 0.317. In the group over 50, "Active member?" makes two pure groups. The group of 50 or younger is nearly pure and becomes a leaf.

Step 5: the same with entropy. The root has p=0.4p = 0.4. With log⁡20.4=−1.3219\log_2 0.4 = -1.3219 and log⁡20.6=−0.7370\log_2 0.6 = -0.7370:

entropy(root)=0.4×1.3219+0.6×0.7370=0.5288+0.4422=0.971\begin{aligned} \text{entropy(root)} &= 0.4 \times 1.3219 + 0.6 \times 0.7370 \\[4pt] &= 0.5288 + 0.4422 = 0.971 \end{aligned}

For "Over 50?", with log⁡20.75=−0.4150\log_2 0.75 = -0.4150, log⁡20.25=−2\log_2 0.25 = -2, log⁡216=−2.585\log_2 \tfrac{1}{6} = -2.585 and log⁡256=−0.263\log_2 \tfrac{5}{6} = -0.263:

entropy(yes)=0.75×0.4150+0.25×2=0.311+0.5=0.811entropy(no)=16×2.585+56×0.263=0.431+0.219=0.650after the split=0.4×0.811+0.6×0.650=0.324+0.390=0.714information gain=0.971−0.714=0.257\begin{aligned} \text{entropy(yes)} &= 0.75 \times 0.4150 + 0.25 \times 2 \\[4pt] &= 0.311 + 0.5 = 0.811 \\[8pt] \text{entropy(no)} &= \tfrac{1}{6} \times 2.585 + \tfrac{5}{6} \times 0.263 \\[4pt] &= 0.431 + 0.219 = 0.650 \\[8pt] \text{after the split} &= 0.4 \times 0.811 + 0.6 \times 0.650 \\[4pt] &= 0.324 + 0.390 = 0.714 \\[8pt] \text{information gain} &= 0.971 - 0.714 = 0.257 \end{aligned}

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 "age>t\text{age} > t?" for many thresholds tt. It sorts the values and tries the points half way between two neighbouring values.

The real ages of the ten customers, from the youngest:

Numerical columns: trying every threshold
CustomerIFEHGJDBCA
Age25293438414551555862
Leftnonoyesnonononoyesyesyes

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:

Gini(age>53)=0Gini(age≤53)=1−(17)2−(67)2=0.2449after the split=0.7×0.2449+0.3×0=0.1714\begin{aligned} \text{Gini}(\text{age} > 53) &= 0 \\[8pt] \text{Gini}(\text{age} \le 53) &= 1 - \left(\tfrac{1}{7}\right)^2 - \left(\tfrac{6}{7}\right)^2 = 0.2449 \\[8pt] \text{after the split} &= 0.7 \times 0.2449 + 0.3 \times 0 \\[4pt] &= 0.1714 \end{aligned}
age > 532535455565

The ten customers by age

squares left, circles stayed

Gini after the split

the lowest wins

The real ages of the ten customers, and the Gini impurity after the question "age > t?" for each of the nine thresholds t half way between two neighbouring ages. The threshold 53 puts the three customers over 53, who all left, into a pure group: the lowest impurity, 0.1714.

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:

  1. Start with all training rows in the root.
  2. Try every feature and every threshold; take the split with the lowest impurity after the split.
  3. Do the same again in each of the two new nodes, with their rows only.
  4. 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

A node holds 6 customers: 3 left and 3 stayed. (a) What is its Gini impurity? (b) What is its entropy? (c) A question splits it into 3 customers who all left and 3 who all stayed. What is the Gini after the split? (d) Is this a good question?

Show a hint
Half and half is the most mixed node. A pure group has impurity 0.
Show the solution

Answer: (a) 0.5; (b) 1; (c) 0; (d) yes, the best possible.

Gini=1−0.52−0.52=0.5entropy=0.5×1+0.5×1=1after the split=0.5×0+0.5×0=0\begin{aligned} \text{Gini} &= 1 - 0.5^2 - 0.5^2 = 0.5 \\[6pt] \text{entropy} &= 0.5 \times 1 + 0.5 \times 1 = 1 \\[6pt] \text{after the split} &= 0.5 \times 0 + 0.5 \times 0 = 0 \end{aligned}

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.

Regression trees
Age253035505560
Balance102030100110120

Without a split the tree predicts the mean, 65, for everybody:

mean=10+20+30+100+110+1206=3906=65\begin{aligned} \text{mean} &= \frac{10 + 20 + 30 + 100 + 110 + 120}{6} \\[4pt] &= \frac{390}{6} = 65 \end{aligned}
squared errors=552+452+352+352+452+552=12550\begin{aligned} \text{squared errors} &= 55^2 + 45^2 + 35^2 \\[4pt] &\quad + 35^2 + 45^2 + 55^2 \\[4pt] &= 12550 \end{aligned}
mean squared error=125506=2091.7\text{mean squared error} = \frac{12550}{6} = 2091.7

With the question "age > 42.5?" (half way between 35 and 50):

left: mean=10+20+303=20squared errors=102+02+102=200right: mean=100+110+1203=110squared errors=102+02+102=200mean squared error=200+2006=66.7\begin{aligned} \text{left: mean} &= \frac{10 + 20 + 30}{3} = 20 \\[4pt] \text{squared errors} &= 10^2 + 0^2 + 10^2 = 200 \\[8pt] \text{right: mean} &= \frac{100 + 110 + 120}{3} = 110 \\[4pt] \text{squared errors} &= 10^2 + 0^2 + 10^2 = 200 \\[8pt] \text{mean squared error} &= \frac{200 + 200}{6} = 66.7 \end{aligned}
0501002030405060
A regression tree with one question, age > 42.5. Each leaf predicts the mean balance of its customers: 20 on the left, 110 on the right. Without the question the tree would predict the mean of all six, 65 (dashed), for everybody. The prediction of a regression tree is a step.

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

A leaf of a regression tree holds four customers with the balances 40, 50, 60 and 90 (thousands). (a) What does the tree predict for a new customer in this leaf? (b) Can a regression tree predict a balance above the largest balance of its training data?

Show a hint
A leaf of a regression tree answers with the mean of its rows.
Show the solution

Answer: (a) 60; (b) no.

40+50+60+904=2404=60\frac{40 + 50 + 60 + 90}{4} = \frac{240}{4} = 60

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

The hyperparameters of DecisionTreeClassifier
HyperparameterDefaultWhat it doesEffect of a larger value
criterion"gini"the impurity measure: "gini", "entropy" (or "log_loss", the same as entropy)(a choice, not a size)
max_depthNone (no limit)the largest number of questions from the root to a leafa deeper, more complex tree: more overfitting
min_samples_split2the smallest number of rows a node must have to be splitfewer splits: a simpler tree
min_samples_leaf1the smallest number of rows every leaf must keepfewer, larger leaves: a simpler tree, smoother probabilities
max_leaf_nodesNonethe largest number of leaves; the best splits are kepta more complex tree
min_impurity_decrease0.0a split is made only if it lowers the weighted impurity by at least this muchfewer splits: a simpler tree
max_featuresNone (all)how many features are tried at each split, chosen at randomNone tries them all; a smaller number makes the tree more random (used in random forests, Topic 30)
class_weightNoneweights for the classes; "balanced" gives the rare class more weight, as in Topic 27(a choice) more recall for the rare class
ccp_alpha0.0cost-complexity pruning: after growing, branches that help too little are cut; a larger value cuts morea smaller tree: less overfitting
splitter"best""best" tries all thresholds; "random" draws them at random(a choice)
random_stateNonethe 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 than ccp_alpha per 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

(a) Which value of 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
Every one of these limits the size of the tree, except the last one.
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 country were coded France =0= 0, Germany =1= 1, Spain =2= 2, the tree could isolate Germany with two questions (">0.5> 0.5?" and "≤1.5\le 1.5?"). 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 keeps products_number as 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

A table for this and the coming topics
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values in scikit-learn
Linear and logistic regression, Ridge, Lasso (22, 26, 27)neededneededsensitivemust be filled
Decision tree (29)not neededneededrobusthandled since version 1.3
Random forest (30, 31)not neededneededrobustsee Topic 30
k-nearest neighbours (32, 33)essential: distancesneededsensitivemust be filled
Support vector machines (35, 36)essential: distancesneededsensitivemust be filled
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost and LightGBM handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivemust 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

(a) Does a decision tree need scaled features? (b) Must the column 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
A tree only asks whether a value is above a threshold. Distances need features on the same scale.
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.

Download

Loading the table ...

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

7.1Step 1: read and look

Python
import pandas as pd

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

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

Output

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

[5 rows x 12 columns]

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

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

Output

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

No missing values 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

Python, continues from the cells above
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

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

Output

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

About 20 percent of the customers left: the classes are unbalanced. 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):

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

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

Output

62.0
359

359 customers are older than 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).

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

print(df.columns.tolist())

Output

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

Eleven features and the target, all numbers.

7.7Step 7: split

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

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

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

print(X_train.shape, X_test.shape)

Output

(8000, 11) (2000, 11)

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

8,000 customers for training, 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

This task continues from the cells above. Take the customers with more than 2 products. Print how many there are, then the share of them who left, rounded to 4 decimals.
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
Python, continues from the cells above
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

Python, continues from the cells above
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?

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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

This task continues from the cells above. Train a tree with 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
Python, continues from the cells above
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

Python, continues from the cells above
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:

Python, continues from the cells above
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 is active_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, and predict_proba is ba+b\frac{b}{a + b}.

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

Python, continues from the cells above
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()
The chart this code draws

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

Python, continues from the cells above
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.

probability of leaving=1493035=0.049\text{probability of leaving} = \frac{149}{3035} = 0.049

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?

Python, continues from the cells above
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

This task continues from the cells above. Take the second test customer (position 1) as a table of one row. Print the class that 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
Python, continues from the cells above
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

Python, continues from the cells above
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.
Python, continues from the cells above
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()
Chart: Accuracy of a tree against its depth

Move max_depth and watch the bank tree. The last step of the slider, 16, stands for no limit at all.

0.750.850.9513579111315

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.

Python, continues from the cells above
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.

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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:

The tuned tree
MeasureLogistic regression (Topic 28)Full treeTree with max_depth=5
Accuracy0.8430.78450.8575
Precision0.69080.45620.7647
Recall0.36390.50380.3969
F1-score0.47670.47880.5226
AUC0.8370.67850.8328

Accuracy

Precision

Recall

F1-score

AUC

The three models on the same 2,000 test customers, measure by measure: logistic regression of Topic 28 (13 features, scaled), the full tree (1,150 leaves) and the tree with max_depth=5 (32 leaves, no scaling). The full tree loses on almost every measure. The tuned tree beats logistic regression on the accuracy, the precision and the F1-score, and comes close on the 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.

Python, continues from the cells above
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

Python, continues from the cells above
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()
Chart: Feature importances of the tuned tree

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:

Python, continues from the cells above
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.

Python, continues from the cells above
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 chart this code draws

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

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

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

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

This task continues from the cells above. Train a tree with 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
Python, continues from the cells above
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

This task continues from the cells above. Print the F1-score of the tuned tree (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
Python, continues from the cells above
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

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns10,000 customers, 12 columns
2. Checkmissing values, repeated rows, text columnsnothing missing; two text columns
3. Dropcolumns without informationcustomer_id
4. Targetthe share of each class20 percent left: unbalanced
5. Outliersfind them, decide: mistake or real359 older customers: real, kept; a tree does not mind them
6. Encodetext to numbersgender 0 and 1, country one-hot; products_number stays a number
7. Splittraining and test data8,000 and 2,000
8. Scaleonly for models that need itnot for a tree
9. First modela simple startthe full tree: overfits (test accuracy 0.7845)
10. Tunehyperparameters with cross-validationmax_depth=5, chosen by the AUC of 5 folds
11. Judgethe measures of Topic 28 on the test dataaccuracy 0.8575, F1 0.5226, AUC 0.8328
12. Explainthe rules and the feature importancesage, 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

(a) Which step of the usual workflow is left out for a tree? (b) Which step is new compared with Topic 28? (c) With which data is max_depth chosen? (d) Which measures judge the tuned tree?

Show a hint
Look at Steps 8 and 12 of the table.
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

Common mistakes
MistakeWhy it is wrongRight
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 log⁡20.3=−1.7370\log_2 0.3 = -1.7370 and log⁡20.7=−0.5146\log_2 0.7 = -0.5146.

Idea. p=0.3p = 0.3; the formulas of Part 3.

Gini=1−0.32−0.72=1−0.09−0.49=0.42entropy=0.3×1.7370+0.7×0.5146=0.5211+0.3602=0.8813\begin{aligned} \text{Gini} &= 1 - 0.3^2 - 0.7^2 \\[4pt] &= 1 - 0.09 - 0.49 = 0.42 \\[8pt] \text{entropy} &= 0.3 \times 1.7370 + 0.7 \times 0.5146 \\[4pt] &= 0.5211 + 0.3602 = 0.8813 \end{aligned}

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:

Gini=1−0.82−0.22=0.32and0after the split=0.5×0.32+0.5×0=0.16\begin{aligned} \text{Gini} &= 1 - 0.8^2 - 0.2^2 = 0.32 \quad \text{and} \quad 0 \\[6pt] \text{after the split} &= 0.5 \times 0.32 + 0.5 \times 0 = 0.16 \end{aligned}

Question B:

Gini=1−0.52−0.52=0.5Gini=1−0.252−0.752=0.375after the split=0.6×0.5+0.4×0.375=0.30+0.15=0.45\begin{aligned} \text{Gini} &= 1 - 0.5^2 - 0.5^2 = 0.5 \\[4pt] \text{Gini} &= 1 - 0.25^2 - 0.75^2 = 0.375 \\[6pt] \text{after the split} &= 0.6 \times 0.5 + 0.4 \times 0.375 \\[4pt] &= 0.30 + 0.15 = 0.45 \end{aligned}

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).

22+302=2630+412=35.541+482=44.5\begin{aligned} \frac{22 + 30}{2} &= 26 \\[6pt] \frac{30 + 41}{2} &= 35.5 \\[6pt] \frac{41 + 48}{2} &= 44.5 \end{aligned}

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.

probability of leaving=1040=0.25\text{probability of leaving} = \frac{10}{40} = 0.25

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).

Python
import pandas as pd

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

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

Output

(10000, 12)
0
0.2037

Why: nothing 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).

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

print(len(df.columns))

Output

12

Why: 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.

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

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

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

print(X_train.shape, X_test.shape)

Output

(7500, 11) (2500, 11)

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

Problem 8: A 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.

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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.

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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()
The chart this code draws

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. 1.A node holds 8 customers: 2 left and 6 stayed. Calculate (a) its Gini impurity, (b) its entropy, with 3 decimals. Use log⁡20.25=−2\log_2 0.25 = -2 and log⁡20.75=−0.4150\log_2 0.75 = -0.4150.

    Show a hint
    p=0.25p = 0.25. Gini is 1−p2−(1−p)21 - p^2 - (1 - p)^2.
    Show one possible solution

    Answer: (a) 0.375; (b) 0.811.

    Gini=1−0.0625−0.5625=0.375entropy=0.25×2+0.75×0.4150=0.5+0.311=0.811\begin{aligned} \text{Gini} &= 1 - 0.0625 - 0.5625 = 0.375 \\[6pt] \text{entropy} &= 0.25 \times 2 + 0.75 \times 0.4150 \\[4pt] &= 0.5 + 0.311 = 0.811 \end{aligned}
  2. 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 1−p2−(1−p)21 - p^2 - (1 - p)^2, 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 p=16p = \tfrac{1}{6}.

    Gini=1−0.028−0.694=0.278after A=0.4×0+0.6×0.278=0.167\begin{aligned} \text{Gini} &= 1 - 0.028 - 0.694 = 0.278 \\[4pt] \text{after A} &= 0.4 \times 0 + 0.6 \times 0.278 = 0.167 \end{aligned}

    Question B: both groups have p=0.6p = 0.6 or p=0.4p = 0.4.

    Gini=1−0.36−0.16=0.48after B=0.5×0.48+0.5×0.48=0.48\begin{aligned} \text{Gini} &= 1 - 0.36 - 0.16 = 0.48 \\[4pt] \text{after B} &= 0.5 \times 0.48 + 0.5 \times 0.48 = 0.48 \end{aligned}

    A is lower, so the tree chooses A.

  3. 3.A tree has the rules: age ≤44.5\le 44.5 and products ≤2.5\le 2.5: stays; age ≤44.5\le 44.5 and products >2.5> 2.5: leaves; age >44.5> 44.5 and not active: leaves; age >44.5> 44.5 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. 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_leaf make 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.

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

    Output

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

    Output

    5457
  3. 7.One-hot encode country inside the table, with drop_first=True and dtype=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), then print(df.columns.tolist()). products_number stays a number.
    Show one possible solution
    Python, continues from the cells above
    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']
  4. 8.Make X (all columns without churn) and y (churn). Split them with test_size=0.3 and random_state=1. Print the shapes of X_train and X_test on one line. This step continues from Step 7.
    Show a hint
    X = df.drop(columns=["churn"]), y = df["churn"], then X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) and print(X_train.shape, X_test.shape).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["churn"])
    y = df["churn"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    print(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.

  1. 9.Train a DecisionTreeClassifier called tree with random_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), then print(tree.score(X_train, y_train)) and print(round(tree.score(X_test, y_test), 4)).
    Show one possible solution
    Python, continues from the cells above
    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.7927
  2. 10.Print the depth of tree, then its number of leaves. This step continues from Step 9.
    Show a hint
    print(tree.get_depth()) and print(tree.get_n_leaves()).
    Show one possible solution
    Python, continues from the cells above
    print(tree.get_depth())
    print(tree.get_n_leaves())

    Output

    23
    1006
  3. 11.Train a tree with max_depth=3 and random_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), then score on each part.
    Show one possible solution
    Python, continues from the cells above
    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.8401
    0.8393
  4. 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 above
    from 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.

  1. 13.Train the tree with max_depth=5 and random_state=42, called final, and put its test predictions into predicted. Print the confusion matrix. This step continues from Step 9.
    Show a hint
    final.fit(X_train, y_train), predicted = final.predict(X_test), then print(confusion_matrix(y_test, predicted)): the truth first.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import confusion_matrix
    
    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]]
  2. 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_score and f1_score with (y_test, predicted); roc_auc_score with the probabilities final.predict_proba(X_test)[:, 1].
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import recall_score, f1_score, roc_auc_score
    
    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
  3. 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), then print(importances.idxmax()) and print(round(importances.max(), 3)).
    Show one possible solution
    Python, continues from the cells above
    importances = pd.Series(final.feature_importances_, index=X.columns)
    
    print(importances.idxmax())
    print(round(importances.max(), 3))

    Output

    age
    0.415
  4. 16.Train a tree with max_depth=2 and random_state=42. Print its test accuracy rounded to 4 decimals, then draw it with plot_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)), then plot_tree(two, feature_names=list(X.columns), class_names=["stays", "leaves"], filled=True) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import 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
    The chart this code draws

15Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.How does a decision tree make a prediction for a new row?

Question 2

2.What is the Gini impurity of a node in which half of the rows belong to each class?

Question 3

3.How does a tree choose the question of a node?

Question 4

4.Which thresholds does a tree try for a numerical feature with the values 10, 20 and 40?

Question 5

5.A tree without limits has a training accuracy of 1.0 and a test accuracy of 0.78. What is it?

Question 6

6.Which change makes a tree simpler?

Question 7

7.Why does a decision tree not need scaled features?

Question 8

8.What does a regression tree predict in a leaf?

Question 9

9.A leaf holds 30 training customers, 12 of whom left. What does predict_proba give for a new customer in this leaf?

Question 10

10.Why does a full tree have a low AUC on the bank data?

Question 11

11.What does feature_importances_ measure?

Question 12

12.With which data is max_depth chosen?

0 of 12 answered.

16Summary

Summary
FormulaMeaning
Gini impurity1−p2−(1−p)21 - p^2 - (1 - p)^20 for a pure node, 0.5 for a half-and-half node
Entropy−plog⁡2p−(1−p)log⁡2(1−p)-p \log_2 p - (1 - p) \log_2 (1 - p)0 for a pure node, 1 for a half-and-half node
A splitnleftn impurityleft+nrightn impurityright\frac{n_{\text{left}}}{n} \, \text{impurity}_{\text{left}} + \frac{n_{\text{right}}}{n} \, \text{impurity}_{\text{right}}the lowest value wins
Information gainentropy before−entropy after\text{entropy before} - \text{entropy after}the largest gain wins
Leaf of a classification treethe share of each classpredict_proba; predict takes the larger share
Leaf of a regression treethe mean of the targeta step function
Summary
CodeWhat 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_alphaother 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
DecisionTreeRegressorthe regression tree

Rules to keep

  1. A tree predicts with a row of yes-or-no questions; each compares one feature with one threshold.
  2. It chooses each question greedily: the split with the lowest weighted impurity (Gini or entropy).
  3. Without limits it overfits: training accuracy 1.0, poor test results, probabilities of only 0 and 1.
  4. Limit it with max_depth, min_samples_leaf or ccp_alpha, chosen with cross-validation on the training data.
  5. A tree needs no scaling and is robust to outliers in the features; text must still be encoded.
  6. 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.