Skip to content

Lesson 9 · Decision Trees

⏱ 63 min read

Suppose we want to predict whether a person will buy a paid subscription on a website. There is information about the visitor:

  • how old they are;
  • whether they have visited the site before;
  • how many pages they have viewed;
  • how many minutes they have spent on the site.

How do we make a decision on the basis of this data? We can come up with a sequence of simple questions:

  1. Has the person visited the site before?
  2. If yes — have they viewed more than three pages?
  3. If no — have they spent more than five minutes on the site?

Depending on the answers we arrive at one of two results: "will buy" or "will not buy". The decision tree is based on exactly this idea.

A decision tree is a machine learning model that makes a decision by means of a sequence of conditions. At every step it checks some feature of the object, chooses the appropriate branch and in the end produces a prediction.

An important feature: the tree does not simply receive an answer from a human who invented the questions. During training the algorithm itself selects the conditions and determines the order in which to check them.

That is what makes the tree a full-fledged machine learning model.

What you will learn in this lecture

After this lecture you will be able to:

  • explain how a decision tree is arranged;
  • understand how the algorithm chooses its questions;
  • compute entropy and the Gini index by hand;
  • compare different ways of splitting the data;
  • understand the difference between classification and regression trees;
  • explain overfitting and the ways of limiting the growth of a tree;
  • solve practice tasks and answer ML interview questions.

Let us start with the structure of a tree, and then go through the mathematics on small examples where every computation can be checked by hand.

1. Why decision trees are needed

1.1. What an object, a feature and a target variable are

Before examining the algorithm, let us define three basic concepts. An object (sample, observation) is the thing for which we want to make a prediction.

For example, one visitor to a website. A feature is a characteristic of the object that we use for the prediction.

For example:

Object Age Has been on the site before Pages viewed Bought a subscription
A 22 Yes 5 Yes
B 41 No 1 No
C 30 Yes 2 Yes
D 19 No 1 No

In this table age, the fact of a previous visit and the number of pages viewed are features.

The target variable is what the model has to learn to predict. In our example that is whether a subscription was bought.

In machine learning the following notation is often used:

  • \(X\) — the features of an object or a set of features;
  • \(y\) — the known correct value of the target variable;
  • \(\hat y\) — the prediction of the model.

The little "hat" over \(y\) is read as "y with a hat" and means precisely the predicted value, not the actual answer. For example:

\[ y=\text{bought},\qquad \hat y=\text{did not buy}. \]

The model has made a mistake: the real answer and the prediction differ.

During training the tree receives examples for which the correct answers are already known. It looks for patterns between the features \(X\) and the target variable \(y\). These patterns are then used to predict the answer for a new object.

1.2. How a tree makes a decision

Let us imagine a simple tree for our task.

A three-level tree diagram: a root question at the top, two condition nodes below it and four prediction leaves at the bottom; one path from the root to a leaf is highlighted in amber
A tree is a sequence of questions. Two branches, "yes" and "no", lead from the root "Visited before?" to the conditions "Pages > 3?" and "Minutes > 5?", and then to four leaves predicting "buy" or "no buy". The amber path follows one visitor: they had visited the site before and had viewed more than three pages, so the prediction is "buy". The labels "root", "branch" and "leaf" mark the root, a branch and a leaf.

This is a simplified scheme: every branch may contain additional conditions and leaves.

It is a scheme invented for the explanation. In a real tree the conditions and the predictions are chosen on the basis of the training data.

Let us follow the path of one visitor. Suppose they have already visited the site before and have viewed five pages.

  1. The tree checks the first question: "Visited the site before?"
  2. The answer is "Yes", so we go along the "Yes" branch.
  3. The next condition: "Viewed more than three pages?"
  4. Five is more than three, so we again choose the "Yes" branch.
  5. We arrive at a leaf with the prediction "Buy".

The model does not have to examine all the features of the object. It checks only the conditions that occur along the chosen path.

1.3. The basic elements of a tree

Term Simple explanation
Root The very first node, from which the tree begins
Node A point of the tree at which a condition may be checked
Internal node A node that checks a condition and sends the object further
Branch A transition from one node to the next
Split condition The rule by which objects are sent into different groups
Leaf A terminal node that produces a prediction

Imagine a real tree growing from the root to the branches and leaves. In machine learning the scheme is inverted relative to the usual picture of a tree: the root is usually at the top and the leaves at the bottom.

An important distinction: a leaf does not ask a new question. It contains a result — for example, the class "will buy" or a numerical forecast such as "expected purchase amount 1500 rubles".

Two cards: on the left an internal node with a condition and two arrows labelled yes and no leading to empty squares; on the right a leaf with an amber dot and the label buy, with no arrows leaving it
An internal node and a leaf. On the left an internal node: it checks a condition about age and sends the object down the "yes" or "no" branch, each of which leads somewhere further. On the right a leaf: it asks no questions and simply holds a result — the class "buy", marked with an amber dot. The difference matters: a node only routes the object, while a leaf produces the prediction.

1.4. Classification and regression

Decision trees solve two main types of task.

Classification. The model chooses a category, that is, a class.

Examples: will buy or will not buy; an email is spam or not spam; the species of a plant is one of several species.

Regression. The model predicts a numerical quantity.

Examples: the price of an apartment, the delivery time, the expected revenue.

In other words, the structure of the tree may be similar, but the values in the leaves and the criteria by which the tree is built differ.

1.5. How a tree differs from other models

We have already examined linear and logistic regression, KNN and SVM. Here we do not need to repeat those topics, but to fix the fundamental differences.

Model How it makes a decision
Linear regression Computes a numerical forecast from a weighted sum of the features
Logistic regression Computes a linear combination of the features and transforms it into a probability with the sigmoid
KNN (k nearest neighbours) Looks for similar training objects and uses their answers
SVM (support vector machine) Builds a separating boundary with certain geometric properties
Decision tree Checks conditions in sequence and reaches a leaf with a forecast

A tree has a useful advantage: its rules can often be read literally. For example:

If a client has bought something before and has visited more than three pages, we predict a purchase.

But the simplicity of the explanation does not guarantee that the forecast is correct. To understand how a tree finds its rules and why it can be wrong, we need to look into training.

2. What a decision tree consists of

2.1. The path from the root to a leaf

Let us consider a more formal representation of a tree:

flowchart TD
    A["Age ≤ 30?"] -->|Yes| B["Visited the site?"]
    A -->|No| C["Leaf: No"]
    B -->|Yes| D["Leaf: Yes"]
    B -->|No| E["Leaf: No"]

This is an example of a structure, not the result of training on real data.

Every object follows a path from the root to one of the leaves. This path is determined by the values of the features of the object.

For example, suppose a visitor is 25 years old and has been on the site before.

  1. We check the condition "Age less than or equal to 30?".
  2. It is true, so we choose the left branch.
  3. We check the condition "Visited the site?".
  4. The answer "Yes" leads to the leaf "Yes".

The final prediction: the visitor will buy the subscription.

Note that the tree does not store a ready answer for every possible person. It stores the rules that send different objects to the corresponding leaves.

2.2. A split

A split is the division of the objects located in one node into two or more groups according to a certain condition. In a simple binary tree a split creates two groups.

For example, there are ten apartments. We divide them by area:

  • area not greater than 50 m²;
  • area greater than 50 m².

Before the split all ten apartments are in one node. After it, five may end up in the left branch and the remaining five in the right one.

This does not mean that the groups will necessarily be equal in size. If nine apartments have an area not greater than 50 m² and one has a larger area, the split gives groups of nine and one object.

The algorithm has to decide which condition to choose. We will study this question in detail in the following sections.

2.3. The depth of a tree

Depth is the number of edges, that is, transitions between nodes, on the path from the root to the node in question. The depth of the root is usually taken to be zero.

Example:

flowchart TD
    L0["Level 0: Age ≤ 30?"] -->|Yes| L1A["Level 1: Yes"]
    L0 -->|No| L1B["Level 1: No"]
    L1A --> L2["Level 2: Visited the site?"]

Here the root has depth 0, its immediate child nodes have depth 1, and the node on the next level has depth 2.

The deeper the tree, the more consecutive conditions it can check. This makes it possible to describe more complex patterns, but it also increases the risk of overfitting.

Important: depth is not the same as the total number of nodes. A tree can be very wide but shallow, or narrow and long.

2.4. The number of nodes and leaves

  • The number of nodes is the number of all nodes of the tree, including internal nodes and leaves.
  • The number of leaves is the number of terminal nodes in which the model produces a prediction.

For a full binary tree, in which every internal node has exactly two children, the following relation holds:

\[ L=I+1, \]

where:

  • \(L\) — the number of leaves;
  • \(I\) — the number of internal nodes.

Why? Every internal node creates two branches. In such a tree the number of transitions equals \(2I\). On the other hand, if the total number of nodes is \(I+L\), the number of transitions equals \(I+L-1\): every node except the root has one parent.

We equate them:

\[ 2I=I+L-1. \]

We subtract \(I\) from both sides:

\[ L=I+1. \]

This property applies specifically to a full binary tree, where every internal node has exactly two children. It should not be transferred automatically to trees with a different structure.

2.5. The training set and a new object

The training set is a collection of examples from which the model learns. It is usually represented as a table: the rows are objects, the columns are features and the known target variable.

During training the tree chooses rules using this data. After training the structure of the tree is fixed.

Then we can give it a new object that was not in the training set. The model goes through the conditions of the tree and returns a forecast.

These are two different processes:

  • Training: find the rules and the values in the leaves.
  • Prediction (inference): apply the rules already found to a new object.

It is exactly this separation that is important to remember: the tree is not rebuilt from scratch on every ordinary prediction.

3. How a tree is trained

3.1. Why we cannot simply build any tree

Suppose we have data about ten visitors to a website. Five bought a subscription, five did not.

We could build a tree with the first question "Is the age greater than 18?". But if all ten visitors are older than 18, the question will not help to separate them: all of them will end up in one group.

We could ask "Is the visitor number less than 6?". If the numbers are random and not connected with the purchase in any way, such a split may be useless as well.

We need conditions that help to separate objects with different answers.

For example, if almost all the visitors who bought something viewed more than three pages, and almost all those who did not buy viewed fewer, this may be a useful condition.

A good split is one after which the groups become more homogeneous with respect to the target variable. The word "homogeneous" means that within each group the answers are similar to each other.

For classification this means that one class predominates in the group. For regression it means that the numerical target values within the group become closer to each other according to the chosen criterion.

3.2. What a split quality criterion is

The algorithm needs some way to assess how good every possible question is.

For this, a split criterion is used — a mathematical measure that makes it possible to compare different ways of dividing the data.

For classification the following are often used:

  • entropy;
  • the Gini index (Gini impurity).

Both quantities assess the impurity of the classes in a node.

For regression, the sum of squared deviations from the mean or the corresponding mean squared error within the nodes is often used.

Later we will examine each measure by hand.

3.3. The greedy algorithm

The word "greedy" may sound strange, but its meaning is fairly simple.

Imagine that we are planning a route and at every crossroads we choose the road that seems best right now, without calculating all possible routes to the end.

The standard algorithm for building a decision tree works in the same way:

  1. It considers the possible splits in the current node.
  2. It assesses the quality of each one.
  3. It chooses the best one according to the chosen criterion.
  4. It repeats the procedure for the child nodes.

The greedy algorithm does not guarantee that the whole tree built in this way will be globally optimal. The best first step does not by itself necessarily lead to the best final result.

Why is this approach used then? Because enumerating all possible tree structures quickly becomes computationally very expensive. Greedy construction makes it possible to find useful trees efficiently on large datasets.

3.4. Recursive partitioning

Recursion is a way of solving a problem in which we repeat a similar procedure for its parts. In our case the algorithm:

  • chooses a split for all the objects in the root;
  • considers the objects in each resulting group separately;
  • again looks for a good split for each group;
  • continues until a stopping condition is met.

In this way the data is successively divided into smaller and smaller groups. For example:

flowchart TD
    R["All 100 objects"] --> A["Group A: 60"]
    R --> B["Group B: 40"]
flowchart TD
    A["Group A: 60"] --> A1["Group A1: 40"]
    A --> A2["Group A2: 20"]
flowchart TD
    B["Group B: 40"] --> B1["Group B1: 10"]
    B --> B2["Group B2: 30"]

This is not necessarily the final structure of the tree. If the groups are still impure, the algorithm may continue splitting. However, the tree must not grow indefinitely. We will look at stopping criteria and pruning in section 8.

4. Trees for classification

Now let us turn to the mathematics.

4.1. What classification is

Classification is a task in which the model has to assign an object to one of a predefined set of categories. For example, for a subscription we have two classes:

  • class 1 — "will buy";
  • class 0 — "will not buy".

Suppose a certain node contains ten objects:

  • 7 objects of class 1;
  • 3 objects of class 0.

The group is impure because both classes are present in it.

If all ten objects belonged to class 1, the node would be pure: from the point of view of the classes it would no longer need to be split.

Special quantities are used to assess such mixing.

4.2. Impurity of a node

Impurity is a numerical measure of how mixed the classes are in a node of a tree. In the context of classification:

  • a pure node contains objects of only one class;
  • an impure node contains several classes.

But how do we turn this concept into a number? Let us consider two groups of ten objects.

  • Group A: 9 objects of class 1 and 1 object of class 0.
  • Group B: 5 objects of class 1 and 5 objects of class 0.

Both groups contain two classes, but in the second they are mixed more strongly. A good impurity measure must reflect this: for group B it must be larger.

Let us examine the two most common measures.

4.3. Entropy

Intuitive explanation

Entropy in decision trees shows how difficult it is to predict the class of a randomly chosen object if we know only the distribution of classes in the node.

If all the objects in a node belong to one class, the uncertainty is zero: the class is already known. If two classes are represented equally, the uncertainty is maximal for a task with these two classes.

You can imagine a box with balls:

  • in the first box there are only red balls — there is no uncertainty;
  • in the second there are 9 red and 1 blue — the colour is almost predictable;
  • in the third there are 5 red and 5 blue — predicting the colour is harder.

Entropy describes this uncertainty numerically.

The entropy formula

\[ H(S)=-\sum_{k=1}^{K}p_k\log_2 p_k. \]

Let us go through the formula symbol by symbol.

Symbol Meaning
\(H(S)\) The entropy of the set of objects \(S\)
\(S\) The objects located in the node under consideration
\(K\) The number of possible classes
\(k\) The index of a particular class
\(p_k\) The share of objects of class \(k\) in the node
\(\log_2\) The logarithm to base 2
\(\sum\) Summation of the expressions for all classes
The minus sign Makes the result non-negative, since for shares between 0 and 1 the logarithm is negative

The share of a class is computed like this:

\[ p_k=\frac{n_k}{N}, \]

where \(n_k\) is the number of objects of class \(k\) and \(N\) is the total number of objects in the node. For example, if seven out of ten objects belong to class 1, the share of that class is:

\[ p_1=\frac{7}{10}=0.7. \]

And for the second class:

\[ p_0=\frac{3}{10}=0.3. \]

Check: \(0.7+0.3=1\). The shares of all classes must add up to one.

Why the logarithm is used

The logarithm makes it possible to measure uncertainty taking the probabilities of events into account. For entropy to base 2 the unit of measurement is called a bit. Here it is enough to understand the following:

  • a more even distribution of classes gives a larger entropy;
  • a distribution in which one class occurs almost always gives a smaller entropy;
  • if only one class is known, the entropy equals zero.

The base of the logarithm affects the scale of the numbers, but not which of two splits is better, as long as the same base is used everywhere.

A special case: what to do with \(\log_2 0\)?

The logarithm of zero is undefined. However, in entropy the following convention is used:

\[ 0\log_2 0=0. \]

This is connected with the limit of the corresponding expression as the probability approaches zero. In practice it means that a class absent from the node makes no contribution to the entropy.

Case 1. The node contains only one class

Let ten objects belong to class 1:

\[ p_1=1,\qquad p_0=0. \]

Then:

\[ H(S)=-\left(1\log_2 1+0\log_2 0\right). \]

Since \(\log_2 1=0\), we get:

\[ H(S)=-(1\cdot0+0)=0. \]

A pure node has entropy 0.

Case 2. Two classes represented equally

Let five objects belong to class 1 and five to class 0.

\[ p_1=p_0=\frac{5}{10}=0.5. \]

We substitute into the formula:

\[ H(S)=-\left(0.5\log_2 0.5+0.5\log_2 0.5\right). \]

Since:

\[ \log_2 0.5=-1, \]

we get:

\[ H(S)=-\left(0.5\cdot(-1)+0.5\cdot(-1)\right)=1. \]

So the entropy equals 1 bit. For two classes the entropy lies in the range from 0 to 1.

Case 3. Seven objects of one class and three of another

Now let us compute the entropy for a distribution of 7 to 3.

\[ H(S)=-\left(0.7\log_2 0.7+0.3\log_2 0.3\right). \]

Approximate values of the logarithms:

\[ \log_2 0.7\approx-0.515, \]
\[ \log_2 0.3\approx-1.737. \]

We multiply each value by the corresponding share:

\[ 0.7\cdot(-0.515)\approx-0.361, \]
\[ 0.3\cdot(-1.737)\approx-0.521. \]

We add them and change the sign:

\[ H(S)\approx-(-0.361-0.521)=0.882. \]

We get approximately \(0.882\) bits. Let us compare the results:

Distribution of classes Entropy
10 and 0 0
9 and 1 ≈ 0.469
7 and 3 ≈ 0.882
5 and 5 1

The closer the shares of the two classes are to equality, the higher the entropy.

What to remember. Entropy measures the impurity of the classes. The smaller it is, the purer the node. When entropy is used as the split criterion, the algorithm aims to reduce the total weighted entropy of the child nodes.

4.4. Gini impurity

Intuitive explanation

The Gini index is another way to measure the impurity of classes.

One useful interpretation: imagine that we choose an object from the node at random and then try to determine its class by choosing a class at random according to the distribution of classes in that node. The Gini index equals the probability that the chosen class does not coincide with the true class of the object.

This is a mathematical interpretation of the measure, not a literal description of how a tree makes a prediction.

The formula

\[ G(S)=1-\sum_{k=1}^{K}p_k^2. \]

Here:

  • \(G(S)\) — the Gini index for the node \(S\);
  • \(K\) — the number of classes;
  • \(p_k\) — the share of objects of class \(k\);
  • \(p_k^2\) — the square of that share;
  • \(\sum\) — the sum of the squares of the shares of all classes.

First we square each share, add up the results, and then subtract the sum from one.

Case 1. A pure node

In the node all ten objects belong to one class:

\[ p_1=1,\qquad p_0=0. \]

We substitute:

\[ G(S)=1-(1^2+0^2)=1-1=0. \]

The Gini index equals zero. There is no impurity.

Case 2. Two classes in equal shares

Let five objects belong to each class:

\[ p_1=p_0=0.5. \]

Then:

\[ G(S)=1-(0.5^2+0.5^2). \]

We compute the squares:

\[ 0.5^2=0.25. \]

We get:

\[ G(S)=1-(0.25+0.25)=0.5. \]

For two classes this is the maximum value of the Gini index.

Case 3. Seven objects of one class and three of another

\[ G(S)=1-(0.7^2+0.3^2). \]
\[ G(S)=1-(0.49+0.09)=0.42. \]

The Gini index equals \(0.42\). Let us compare:

Distribution of classes Entropy Gini index
10 and 0 0 0
9 and 1 ≈ 0.469 0.18
7 and 3 ≈ 0.882 0.42
5 and 5 1 0.5

Both measures show the same qualitative direction: equal shares of the classes correspond to the greatest impurity, and a pure node to zero.

However, the numerical values differ, because the formulas are different.

A plot with two symmetric arches: a tall amber entropy curve and a light blue Gini index curve about half as high, both peaking in the middle and reaching zero at the ends
Entropy and the Gini index as functions of the class share. The horizontal axis is the share of class 1, the vertical axis is impurity. Both curves are zero at the ends, where the node is pure, and reach their maximum exactly in the middle, where the classes are mixed most. The amber entropy curve runs above the light blue Gini curve, but they behave in the same way: the closer to the middle, the worse the node.

4.5. Classification error

For comparison, let us consider one more measure. The classification error in a node is defined as the share of objects that do not belong to the most numerous class:

\[ E(S)=1-\max_k p_k. \]

Here \(\max_k p_k\) means the largest of the class shares.

For example, if a node contains 7 objects of class 1 and 3 objects of class 0, the most numerous class occupies a share of \(0.7\):

\[ E(S)=1-0.7=0.3. \]

If all the objects belong to one class:

\[ E(S)=1-1=0. \]

If the two classes are represented equally:

\[ E(S)=1-0.5=0.5. \]

Why is this measure usually less sensitive to small changes in the distribution than entropy and the Gini index?

Because it takes into account only the share of the most numerous class. For example, as long as one class remains predominant, a small change in the share of the other class may hardly affect the estimate.

Entropy and the Gini index take the distribution of all classes into account through more sensitive mathematical expressions.

4.6. Comparing the three criteria

Criterion Formula What it measures Value for a pure node
Entropy \(-\sum p_k\log_2 p_k\) The uncertainty of the class distribution 0
Gini index \(1-\sum p_k^2\) The impurity of the classes 0
Classification error \(1-\max_k p_k\) The share of objects not of the most numerous class 0

For binary classification the maxima are:

  • entropy — 1 bit;
  • the Gini index — 0.5;
  • classification error — 0.5.

With a larger number of classes the maximum values may be different.

Why are different criteria needed? All of them assess impurity, but they react to the class distribution in different ways. In real implementations of trees, entropy or Gini is often used to choose splits, whereas classification error may be applied, for example, when assessing the quality of ready-made predictions.

5. How to choose the best split

We can already assess the impurity of a single node. Now let us solve a more important problem: how do we compare several possible questions?

5.1. Before the split and after the split

Imagine that the root of the tree contains ten objects:

  • 5 objects of the class "will buy";
  • 5 objects of the class "will not buy".

The entropy of the root is:

\[ H_{\text{before}}=1. \]

We are considering two possible conditions. Option A: after the division we get two groups, each containing 5 objects of one class.

Option B: after the division we get two groups, each containing 5 objects, but the classes are still represented equally.

In option A the split separated the classes completely. In option B nothing changed from the point of view of the class distribution.

To choose between them, let us compare the impurity before and after the split.

5.2. The weighted impurity of the child nodes

After the split child nodes appear. Their impurity has to be combined into a single estimate. For two child nodes:

\[ H_{\text{after}} = \frac{N_L}{N}H(L) + \frac{N_R}{N}H(R). \]

Notation:

  • \(N\) — the number of objects before the split;
  • \(N_L\) — the number of objects in the left child node;
  • \(N_R\) — the number of objects in the right child node;
  • \(H(L)\) — the entropy of the left node;
  • \(H(R)\) — the entropy of the right node.

Since all the objects end up in one of the two child nodes, \(N=N_L+N_R\). Why are weights used? Because a node of 90 objects must influence the overall estimate more strongly than a node of 10 objects.

For example, let the first child node contain 9 objects and the second 1. Their entropies equal 0 and 1 respectively. The weighted entropy:

\[ H_{\text{after}} = \frac{9}{10}\cdot0+ \frac{1}{10}\cdot1 =0.1. \]

If we simply averaged the entropies without taking the sizes of the nodes into account, we would get:

\[ \frac{0+1}{2}=0.5. \]

That would mean that a node of one object has the same influence as a node of nine. For assessing the distribution of all objects this is not what we need.

5.3. Information gain

Information gain is the reduction of entropy after a split.

The formula:

\[ IG=H_{\text{before}}-H_{\text{after}}. \]

Here:

  • \(IG\) — the information gain;
  • \(H_{\text{before}}\) — the entropy of the original node;
  • \(H_{\text{after}}\) — the weighted entropy of the child nodes.

The more a split reduces the entropy, the higher the information gain. For the Gini criterion the reduction of impurity can be computed analogously:

\[ \Delta G=G_{\text{before}}-G_{\text{after}}. \]

Here \(G_{\text{after}}\) is the weighted Gini index of the child nodes. In both cases we compare the original impurity with the impurity after the division.

Three rows of split diagrams and three impurity bars: a tall one before the split and two lower ones after two candidate splits, with gain arrows of different lengths between the levels
Information gain for two splits. At the top the parent node with four objects of each class and the bar of its impurity ("before"). Below, two candidate splits: in "split A" the classes remain mixed inside the groups, while in "split B" the left group becomes completely pure. The lower the bar after the split, the longer the gain arrow: "gain B" is noticeably larger than "gain A". A good split reduces impurity more.

5.4. A complete numerical example

Let us consider eight visitors to a website. Four bought a subscription and four did not. For convenience let us denote the purchase class as \(+\), and the absence of a purchase as \(-\).

Visitor Viewed more than 3 pages? Spent more than 5 minutes? Class
1 Yes Yes +
2 Yes Yes +
3 Yes No +
4 Yes No −
5 No Yes +
6 No No −
7 No No −
8 No No −

In the original node there are four positive and four negative objects. Consequently:

\[ p_+=\frac48=0.5,\qquad p_-=\frac48=0.5. \]

The original entropy:

\[ H_{\text{before}}=-\left(0.5\log_2 0.5+0.5\log_2 0.5\right)=1. \]

Now let us compare two splits.

Option A: "Viewed more than three pages?"

The left group is the answer "Yes": visitors 1, 2, 3, 4. It contains three objects of class \(+\) and one of class \(-\).

\[ p_+=\frac34=0.75,\qquad p_-=\frac14=0.25. \]

The entropy of the left group:

\[ H(L)=-\left(0.75\log_2 0.75+0.25\log_2 0.25\right). \]

We use the approximate values:

\[ \log_2 0.75\approx-0.415, \qquad \log_2 0.25=-2. \]

Then:

\[ H(L)\approx-\left(0.75\cdot(-0.415)+0.25\cdot(-2)\right). \]
\[ H(L)\approx-(-0.311-0.5)=0.811. \]

The right group is the answer "No": visitors 5, 6, 7, 8. It contains one object of class \(+\) and three of class \(-\). The distribution is symmetric, therefore:

\[ H(R)\approx0.811. \]

Each group contains four objects. The weighted entropy:

\[ H_{\text{after,A}} = \frac48\cdot0.811+ \frac48\cdot0.811. \]
\[ H_{\text{after,A}}=0.811. \]

The information gain:

\[ IG_A=1-0.811=0.189. \]

Option B: "Spent more than five minutes?"

Let us consider the same eight objects, but divide them by time. The group "Yes": visitors 1, 2, 5.

All three belong to class \(+\). Therefore:

\[ H(L)=0. \]

The group "No": visitors 3, 4, 6, 7, 8. Here there are two objects of class \(+\) and three of class \(-\).

\[ p_+=\frac25=0.4,\qquad p_-=\frac35=0.6. \]

The entropy:

\[ H(R)=-\left(0.4\log_2 0.4+0.6\log_2 0.6\right). \]

We use:

\[ \log_2 0.4\approx-1.322, \qquad \log_2 0.6\approx-0.737. \]

We substitute:

\[ H(R)\approx-\left(0.4\cdot(-1.322)+0.6\cdot(-0.737)\right). \]
\[ H(R)\approx-(-0.529-0.442)=0.971. \]

Now we take the sizes of the groups into account: there are three objects on the left and five on the right.

\[ H_{\text{after,B}} = \frac38\cdot0+\frac58\cdot0.971. \]
\[ H_{\text{after,B}}\approx0.607. \]

The information gain:

\[ IG_B=1-0.607=0.393. \]

Comparing the results

Indicator Option A Option B
Entropy before the split 1 1
Entropy after the split ≈ 0.811 ≈ 0.607
Information gain ≈ 0.189 ≈ 0.393

Option B wins: it reduces the weighted entropy more strongly.

This clearly demonstrates an important principle: the best split does not necessarily create two groups equal in size. It must improve the separation of the objects by class according to the chosen criterion.

Note that we compared only two candidates. In real training a tree may consider many thresholds and features, and then choose the best of the admissible options.

5.5. Must the information gain always be large?

No. Sometimes no feature makes it possible to separate the objects well. Then the best of the available options may give only a small reduction of impurity.

Besides that, some algorithms restrict the growth of a tree if the improvement is too small. In that case the tree may stop even if the data is not separated perfectly.

Different implementations may also use different criteria: for example, entropy, the Gini index, or a criterion based on the reduction of the squared error for regression.

6. Features and split thresholds

6.1. Numerical features

A numerical feature is a characteristic whose value is expressed by a number. Examples:

  • age: 18, 25, 43;
  • the price of a product: 100, 500, 1200;
  • time on the site: 1.5 minutes, 4 minutes, 8 minutes.

For a numerical feature a tree often uses a condition of the form:

\[ x_j\le t. \]

Let us go through the notation:

  • \(x_j\) — the value of the feature with index \(j\) for the object under consideration;
  • \(j\) — the index of the feature;
  • \(t\) — the threshold, the number with which the value of the feature is compared;
  • \(\le\) — "less than or equal to".

For example:

\[ x_2\le30. \]

If \(x_2\) denotes age, the condition means "age not greater than 30 years". If the condition is true, the object goes along one branch; if it is false, along the other.

6.2. How the threshold is chosen

Let the ages of the visitors be:

\[ 18,\ 22,\ 25,\ 31,\ 37,\ 42. \]

Possible thresholds can be chosen between neighbouring distinct values. For example:

  • between 18 and 22 — threshold 20;
  • between 22 and 25 — threshold 23.5;
  • between 25 and 31 — threshold 28;
  • between 31 and 37 — threshold 34;
  • between 37 and 42 — threshold 39.5.

Why can midpoints be used?

If the data contains no values between 25 and 31, then the thresholds 26, 28 or 30 will divide this particular training set in the same way: all observations with an age up to and including 25 end up on the left, and those from 31 on the right.

Therefore there is no need to check an infinite number of thresholds. For standard splits on a single numerical feature it is enough to consider a finite number of candidates corresponding to the different ways of dividing the observed values.

A horizontal axis with feature values, six dots of two classes, five dashed candidate threshold lines and five information gain bars of different heights, the tallest bar labelled as the best split
Trying thresholds and choosing the best one. Feature values lie along the "feature value" axis: grey objects of one class on the left, amber objects of the other class on the right. The dashed lines are five candidate thresholds between neighbouring values, and the bars below them are the information gain of each candidate. The middle bar is the tallest: it is declared the best split, and after it both groups turn out pure.

In some implementations the ways of searching for candidates differ: for example, approximate methods may be used for large datasets.

6.3. Categorical features

A categorical feature is a feature that takes values from a set of categories. Examples:

  • device type: computer, smartphone, tablet;
  • payment method: card, e-wallet, bank transfer;
  • city: Cairo, Hurghada, Alexandria.

For a binary categorical feature the condition is simple: "is the device a smartphone?" But what should be done if there are more than two categories?

Different approaches are possible. An implementation may check a single category, divide the set of categories into subsets, or use another internal representation. Support for categorical features directly depends on the algorithm and the library.

For example, not all implementations of classical CART work automatically with raw string categories: sometimes the categories have to be converted into a numerical representation beforehand.

6.4. Why one feature can be used several times

Suppose a tree first divides the visitors by age:

\[ \text{age}\le30. \]

In the group aged 30 or younger the algorithm may use age again:

\[ \text{age}\le22. \]

This is not a contradiction. The first condition divides all the objects into two large groups, and the second refines one of them further.

In this way the tree builds a decision region out of several consecutive conditions.

On the left a plane of two features cut by one vertical and two horizontal lines into four coloured rectangular regions with dots; on the right a tree with three conditions and four leaves of the same colours
A tree divides the space into rectangular regions. On the left the plane of two features x1 and x2: the vertical boundary x1 ≤ 3 and two horizontal ones — x2 ≤ 4 in the left part and x2 ≤ 6 in the right part — cut it into four rectangles, each tinted with the colour of its class. On the right the same rule is written as a tree: the root x1 ≤ 3, the nodes x2 ≤ 4 and x2 ≤ 6, and four leaves of the same colours. Any tree over numerical features produces such stepped rectangular boundaries.

6.5. Binary split

A binary split is the division of a node into two child groups. For example:

flowchart TD
    A["Price ≤ 1000?"] -->|Yes| Y["Yes"]
    A -->|No| N["No"]

Many popular implementations of trees use binary splits. However, this is a common approach, not a universal property of absolutely all possible decision trees.

7. Trees for regression

Until this point we have considered classification: the tree predicted a class. Now let us learn to work with numerical targets.

7.1. What a regression tree predicts

Suppose we want to predict the price of an apartment from its area.

Apartment Area, m² Price, millions
A 30 3
B 35 3.5
C 40 4
D 70 7
E 80 8

The target variable is the price, measured in millions of rubles. This is a regression task, because the correct answer is a number and not a category.

A regression tree also divides the objects by conditions. But in a leaf it stores a numerical forecast rather than the name of a class.

7.2. Why the mean is often used in a leaf

Let us consider three apartments whose prices are 3, 3.5 and 4 million rubles. If we have to predict one and the same number for all three apartments, which value should we choose?

When the squared error is used, the optimal constant prediction is the arithmetic mean. The arithmetic mean is the sum of the values divided by their number:

\[ \bar y=\frac{1}{N}\sum_{i=1}^{N}y_i. \]

Here:

  • \(\bar y\) — the mean value of the target;
  • \(N\) — the number of objects;
  • \(y_i\) — the target value of the object with index \(i\);
  • \(\sum\) — the addition of all the target values.

For our three apartments:

\[ \bar y=\frac{3+3.5+4}{3} =\frac{10.5}{3}=3.5. \]

So the prediction for every apartment in this leaf will be 3.5 million rubles.

This is not a claim that the price of every apartment equals 3.5 million. It is a single prediction chosen so as to minimise the sum of squared deviations within the group.

With other criteria and model settings the value in a leaf may be determined differently.

7.3. Squared error

For a numerical target the square of the deviation of the prediction from the correct value is often used:

\[ (y_i-\hat y_i)^2. \]

Here:

  • \(y_i\) — the actual price;
  • \(\hat y_i\) — the prediction of the model;
  • \(y_i-\hat y_i\) — the difference between the fact and the prediction;
  • the square makes negative and positive errors non-negative and penalises large deviations more strongly.

If the actual price is 3 million and the prediction is 3.5 million:

\[ (3-3.5)^2=(-0.5)^2=0.25. \]

If the actual price is 4 million:

\[ (4-3.5)^2=(0.5)^2=0.25. \]

Both errors are equal in magnitude after squaring. For a node it is convenient to compute the sum of squared deviations:

\[ SSE=\sum_{i=1}^{N}(y_i-\bar y)^2. \]

SSE stands for Sum of Squared Errors. In this expression we measure the deviations of the target values from the mean in the node.

An example of computing by hand

The prices are 3, 3.5 and 4 million rubles. We have already found the mean:

\[ \bar y=3.5. \]

Now let us compute the deviations:

  • \(3-3.5=-0.5\);
  • \(3.5-3.5=0\);
  • \(4-3.5=0.5\).

We square them:

  • \((-0.5)^2=0.25\);
  • \(0^2=0\);
  • \(0.5^2=0.25\).

We add them up:

\[ SSE=0.25+0+0.25=0.5. \]

We obtained a sum of squared deviations equal to \(0.5\) in squared units of the price. If the mean squared error within the node needs to be compared, the sum can be divided by the number of objects:

\[ MSE=\frac{SSE}{N}=\frac{0.5}{3}\approx0.167. \]

Here MSE is the mean value of the squared deviations. It is important not to confuse it with SSE: the sum and the mean differ by division by the number of objects.

7.4. How a split improves regression predictions

Let us go back to the five apartments:

Area Price
30 3
35 3.5
40 4
70 7
80 8

At first all the apartments are in one leaf. The mean price:

\[ \bar y=\frac{3+3.5+4+7+8}{5} =\frac{25.5}{5}=5.1. \]

The tree predicts 5.1 million for every apartment. Let us compute SSE:

\[ \begin{aligned} SSE_{\text{before}}={}&(3-5.1)^2+(3.5-5.1)^2\\ &+(4-5.1)^2+(7-5.1)^2\\ &+(8-5.1)^2. \end{aligned} \]

We compute the terms:

\[ \begin{aligned} SSE_{\text{before}}={}&4.41+2.56+1.21\\ &+3.61+8.41=20.2. \end{aligned} \]

Now let us divide the apartments by area:

  • the left group: area not greater than 50 m²;
  • the right group: area greater than 50 m².

In the left group the prices are 3, 3.5 and 4. The mean equals 3.5, and SSE has already been computed:

\[ SSE_L=0.5. \]

In the right group the prices are 7 and 8. The mean:

\[ \bar y_R=\frac{7+8}{2}=7.5. \]

The sum of squared deviations:

\[ SSE_R=(7-7.5)^2+(8-7.5)^2. \]
\[ SSE_R=0.25+0.25=0.5. \]

The total error after the split:

\[ SSE_{\text{after}}=SSE_L+SSE_R=0.5+0.5=1. \]

The reduction of the error:

\[ \Delta SSE=20.2-1=19.2. \]

This is a substantial improvement: within each group the prices are much closer to each other than in the original set.

The principle of a regression tree: it looks for splits that reduce the spread of the target values within the child nodes according to the chosen criterion.

Two panels with the same points on a cost versus distance plot: on the left one horizontal mean prediction line, on the right two horizontal lines at different heights joined by a vertical segment at the split threshold
A single mean versus a stepwise prediction. Both panels show the same points: three flats with a low price and two with a high price. On the left the tree has one leaf ("one leaf"), so the prediction is the same for everyone — a horizontal line at the mean. On the right, after the split at "split = 5", there are two leaves and the prediction becomes a step: the low mean "mean A" on the left, the high mean "mean B" on the right. The step follows the data more closely.

In this example we are not claiming that area is the only or always the best feature for the price of an apartment. We have merely shown how the criterion works on a specific dataset.

8. Overfitting and controlling complexity

8.1. What overfitting is

Imagine that we are training a tree on data about subscription purchases. A small tree may discover patterns such as:

  • visitors who have bought things before take out a subscription more often;
  • visitors who study a page for a long time make a purchase more often.

But if the tree is allowed to grow without restrictions, it may start memorising individual training examples instead of looking for general patterns.

For example, the tree may build a rule:

If the age equals 23, the number of pages viewed equals 7 and the time on the site equals 8.4 minutes, then a purchase will be made.

It is possible that such a visitor really did buy a subscription in the training set. But from a single observation one cannot conclude that all future visitors with similar characteristics will necessarily buy it.

Overfitting is a situation in which the model fits the training data too closely and therefore performs worse on new examples it has not seen before.

This does not mean that the model will always predict new data badly. The point is that excessive fitting creates a risk of losing quality on new examples.

8.2. Generalization

Generalization is the ability of a model to find patterns that work not only on the training data but also on new objects from the same target task.

Quality is usually assessed on separate data that was not used during training. For example:

  • the training set — 800 visitors;
  • the validation set — 200 other visitors.

The tree is built from the first 800 objects, and its quality is checked on the remaining 200. Important: good quality on the training data does not by itself prove good generalization.

8.3. Why a deep tree can overfit

The deeper the tree, the more consecutive conditions it can use.

In the limiting case a classification tree can create separate leaves for many individual training objects and memorise their classes correctly.

However, new data may contain other combinations of features, noise and random deviations. Therefore increasing the depth may first improve the predictions and then stop helping or even make the quality on new data worse.

Let us consider a conditional example.

The complexity of a tree and the quality of a model. These are illustrative values, not the results of a real experiment: the deeper the tree, the lower the error on the training data, but the error on new data does not have to decrease.

A plot with two error curves against depth: the light blue training curve decreases monotonically, the amber test curve first decreases and then rises, its minimum marked by a dashed line
Tree depth and error. The horizontal axis is depth, the vertical axis is error. The light blue training error curve ("train") decreases all the way: a deep tree nearly memorises the training set. The amber test error curve ("test") also decreases at first but then rises again. The dashed line marks the best point ("best depth") — the moment after which making the tree more complex starts to hurt.

In this educational example:

  • depth 1 — the tree is too simple and misses part of the patterns;
  • depth 3 — the tree is complex enough and generalizes the data well;
  • depth 6 — the tree almost memorises the training set, but the quality on new data gets worse.

This is an illustration of possible behaviour, not a universal law for any dataset.

8.4. Parameters that limit the complexity of a tree

Machine learning libraries provide hyperparameters that make it possible to limit the growth of a tree.

Parameter What it means
max_depth The maximum admissible depth of the tree
min_samples_split The minimum number of objects in a node required to attempt to split it
min_samples_leaf The minimum number of objects that must remain in each leaf
max_leaf_nodes The maximum admissible number of leaves, if the parameter is supported by the implementation

Let us look at them in more detail.

max_depth

If you set max_depth = 3, the tree cannot grow deeper than the set limit.

This does not mean that it will necessarily have a depth of exactly 3. If further splits are unnecessary or impossible, the tree may stop earlier.

min_samples_split

Suppose min_samples_split = 10 is set. Then a node in which only 6 objects remain will not be split, even if the algorithm is able to find a formally suitable condition.

This restriction helps to avoid excessively small groups.

min_samples_leaf

Suppose min_samples_leaf = 5. Then every split must leave at least five objects in each child leaf or subtree at the corresponding step.

This differs from min_samples_split: the first parameter limits the ability to split the current node, while the second requires the result of the split to contain a sufficient number of objects on each side.

max_leaf_nodes

If a limit of 10 leaves is set, the tree cannot create more than ten terminal nodes. The number of leaves limits the number of distinct regions of the feature space for which the tree can store separate predictions.

8.5. Pre-pruning

Pre-pruning is stopping the growth of a tree before it becomes excessively complex. For example, a tree may stop because:

  • the maximum depth has been reached;
  • there are too few objects in the node;
  • a further split does not give a sufficient improvement according to the chosen criterion.

The advantage: there is no need to build an increasingly complex tree that then has to be simplified.

The drawback: restrictions that are too strict may stop a useful split. The algorithm may fail to build an important structure that could have been discovered at later steps.

8.6. Post-pruning

Post-pruning is the simplification of a tree that has already been built.

For example, the tree first grew to a great depth. Then the algorithm assesses which subtrees can be replaced by leaves without an excessive loss of quality.

A subtree is a part of a tree consisting of a certain node and all of its descendants. The idea of post-pruning: if a complex branch hardly improves the predictions, it can be removed and replaced by a simpler rule.

Two tree diagrams: on the left a large tree with two faded subtrees and cut marks on the arrows leading to them; on the right the same tree with amber leaves in place of those subtrees
Post-pruning: a large tree and its simplification. On the left the tree before pruning: two right-hand branches have grown too large, so they are drawn faded, and the arrows leading to them carry cut marks — these subtrees are meant to be removed. On the right the same tree after pruning: the two subtrees are replaced by amber leaves. The tree has become simpler, while the top part and the other branches are unchanged.

In some algorithms post-pruning uses a special penalty for the complexity of the tree. The specific methods and criteria depend on the implementation.

8.7. The bias-variance trade-off

These concepts help to understand why a model that is too simple and a model that is too complex can both perform poorly.

Bias is the error connected with the fact that the model is too simple and cannot express the necessary patterns.

Variance is the sensitivity of the model to changes in the training data. For example:

  • a very small tree may be too simple and fail to take important patterns into account;
  • a very deep tree may change strongly in response to small changes in the sample;
  • a tree of moderate complexity may find a better balance between these problems.

This does not mean that there is always one universal optimal depth. It is chosen with the data, the task and the assessment of quality on new examples in mind.

9. A complete walkthrough: from training to prediction

Now let us assemble the whole algorithm into one sequence.

Four cards connected by arrows: a data table with dots of two classes, a square with a split threshold, a small tree, and a prediction card with a dot and a forecast
The complete walkthrough from data to prediction. Four cards from left to right: "data" — the table of training data, "training" — choosing the split threshold, "tree" — the resulting tree with two leaves, "prediction" — a new object travels down the tree and receives a prediction marked with an amber dot. This scheme is the plan of the whole section: each step is discussed separately below.

Let us consider a small task: to predict whether a visitor will buy a subscription, based on the number of pages viewed.

9.1. Step 1. Obtain the training data

Visitor Pages viewed Bought
A 1 No
B 2 No
C 3 No
D 4 Yes
E 5 Yes
F 6 Yes

We have six objects, one numerical feature and a binary target variable.

9.2. Step 2. Consider the possible splits

The possible thresholds are located between neighbouring values of the feature:

\[ 1,\ 2,\ 3,\ 4,\ 5,\ 6. \]

The candidates for the threshold:

\[ 1.5;\quad 2.5;\quad 3.5;\quad 4.5;\quad 5.5. \]

Let us consider the threshold \(3.5\):

  • on the left are the visitors who viewed 1, 2 and 3 pages;
  • on the right those who viewed 4, 5 and 6 pages.

9.3. Step 3. Compute the quality of a split

In the root there are three objects of the class "No" and three of the class "Yes". The original entropy equals 1. After the split:

  • the left group contains only the class "No";
  • the right group contains only the class "Yes".

The entropy of both groups equals zero. Consequently:

\[ H_{\text{after}} =\frac36\cdot0+\frac36\cdot0=0. \]

The information gain:

\[ IG=1-0=1. \]

This is a perfect split for the training set.

9.4. Step 4. Choose the best split

If other admissible splits give a smaller information gain, the algorithm chooses the threshold \(3.5\). In our example we get:

flowchart TD
    A["Pages ≤ 3.5?"] -->|Yes| B["No"]
    A -->|No| C["Yes"]

9.5. Step 5. Repeat the procedure

In this example the child nodes are already pure: only one class remains in each of them. No further splits are needed, so training can finish.

With more complex data the child nodes often contain several classes. Then the algorithm continues searching for conditions in each group.

9.6. Step 6. Assign predictions to the leaves

The left leaf stores the prediction "No" and the right one "Yes".

In real implementations a leaf may also store the distribution of classes, the number of objects of each class and other information needed for predictions.

9.7. Step 7. Predict the answer for a new object

A new visitor has viewed 4 pages. We pass them through the tree:

  1. We check: \(4\le3.5\)?
  2. No, the condition is false.
  3. We move to the right leaf.
  4. We obtain the prediction "Yes".

The tree predicts that the visitor will buy the subscription.

But there is an important caveat here: a perfect separation of the training data does not prove that the prediction will be error-free on new data. Our example was chosen specifically to demonstrate the mechanics of the algorithm.

10. Practical examples

10.1. Classification: predicting a subscription purchase

Let us build a small tree by hand. We have the data:

Visitor Been on the site before? Pages viewed Bought a subscription
A Yes 5 Yes
B Yes 2 Yes
C Yes 4 Yes
D Yes 1 No
E No 1 No
F No 2 No
G No 6 Yes
H No 3 No

First let us find the class distribution. Four bought a subscription and four did not.

\[ H_{\text{root}}=1. \]

Let us try splitting the data by the feature "Been on the site before?". The "Yes" group: A, B, C, D.

It contains three purchases and one non-purchase. Its entropy:

\[ H_{\text{yes}}\approx0.811. \]

The "No" group: E, F, G, H. It contains one purchase and three non-purchases. The entropy is also approximately \(0.811\).

The weighted entropy:

\[ H_{\text{after}}= \frac48\cdot0.811+ \frac48\cdot0.811 =0.811. \]

The information gain:

\[ IG=1-0.811=0.189. \]

Now let us consider the condition "Viewed more than 3 pages?". The "Yes" group: A, C, G.

All three bought a subscription, so the entropy is zero. The "No" group: B, D, E, F, H.

It contains one object of the class "Yes" and four of the class "No". The shares:

\[ p_{\text{yes}}=\frac15=0.2,\qquad p_{\text{no}}=\frac45=0.8. \]

Entropy:

\[ H_{\text{no}}= -\left(0.2\log_2 0.2+ 0.8\log_2 0.8\right) \approx0.722. \]

The weighted entropy:

\[ H_{\text{after}}= \frac38\cdot0+\frac58\cdot0.722 \approx0.451. \]

The information gain:

\[ IG=1-0.451=0.549. \]

At the first step the number of pages viewed beats the previous-visit feature on information gain. We get the initial structure:

         Pages > 3?
           /      \
          No       Yes
          |         |
       Mixed      "Yes"
       group

In the left group five objects remain, one of which bought a subscription and four of which did not. If we allow further growth, the tree can look for an additional condition inside this group.

But we do not have to build the tree until the data is completely separated. During training a depth limit, a minimum number of objects in the leaves, or another stopping criterion can be applied.

What about predictions for several visitors?

  • A visitor with 5 pages viewed will land in the right leaf and get the prediction "Yes".
  • A visitor with 2 pages will land in the left branch, where there is no definite answer yet. If we stopped growth here, the leaf has to output a class by the accepted rule — for example, the most numerous class "No".
  • If the tree keeps growing, the answer for the second visitor may be determined by additional conditions.

This example shows how a tree chooses a feature and then refines the rules inside the remaining groups.

10.2. Regression: predicting the delivery cost

Now suppose we predict the delivery cost in conventional monetary units from the distance.

Order Distance, km Cost
A 1 100
B 2 110
C 3 120
D 8 300
E 9 310

For now all the objects are in a single leaf. The average cost:

\[ \bar y=\frac{100+110+120+300+310}{5} =\frac{940}{5}=188. \]

The model predicts 188 for every order. But this is not a very good single prediction: the cost of the first three orders is considerably lower than that of the last two.

Let us split the orders by distance, using a threshold of 5 km. The left group: 100, 110, 120.

\[ \bar y_L=\frac{100+110+120}{3}=110. \]

Its SSE:

\[ SSE_L=(100-110)^2+(110-110)^2+(120-110)^2. \]
\[ SSE_L=100+0+100=200. \]

The right group: 300, 310.

\[ \bar y_R=\frac{300+310}{2}=305. \]

Its SSE:

\[ SSE_R=(300-305)^2+(310-305)^2=25+25=50. \]

The total sum of squared errors after the split:

\[ SSE_{\text{after}}=200+50=250. \]

Before the split:

\[ \begin{aligned} SSE_{\text{before}}={}&(100-188)^2+(110-188)^2\\ &+(120-188)^2+(300-188)^2\\ &+(310-188)^2. \end{aligned} \]

Calculating:

\[ SSE_{\text{before}}=7744+6084+4624+12544+14884=45880. \]

The reduction in error:

\[ \Delta SSE=45880-250=45630. \]

The split sharply reduced the error on the training data. As a result the tree may look like this:

       Distance ≤ 5 km?
          /          \
        Yes            No
         |              |
  Prediction: 110  Prediction: 305

If a new order has a distance of 2.5 km, it lands in the left leaf and gets the prediction 110. If the distance is 8.5 km, it lands in the right leaf with the prediction 305.

The values 110 and 305 are the average costs in the corresponding training groups. The real cost of a new order may differ.

11. Advantages and limitations of decision trees

11.1. Advantages

1. Interpretability.

Many trees can be explained by a sequence of understandable rules. We can trace the path from the root to a leaf and see why the model produced a particular prediction.

For example:

The visitor viewed more than three pages — the model predicted a purchase.

2. The ability to describe non-linear dependencies.

A linear model is limited by the form of dependence that its formula defines. A tree, by contrast, can build complex rules that change depending on previous conditions.

For example, for young visitors one feature may matter, and for older ones another. 3. Feature standardization is usually not required.

Standardization is a transformation of features in which their values are brought to a comparable scale, often with zero mean and unit standard deviation.

For KNN and SVM the scale of the features can substantially affect distances and the geometry of the separating boundary. In ordinary trees the decision is based on comparisons of feature values with thresholds, so changing the scale of one feature usually does not change the meaning of the available splits.

For example, if age is expressed in years or in months, then with the corresponding transformation the threshold can be changed from 30 years to 360 months while preserving the same separation of objects.

This does not mean that any feature transformations are completely irrelevant for every tree implementation. The point is specifically about ordinary scaling that preserves the order of values.

4. Support for numerical predictions and classification. Trees can be used both to predict classes and to predict numbers.

11.2. Limitations

1. Instability of the structure.

A small change in the training data can lead to a different first split. After that the composition of the child nodes changes, and therefore so do the subsequent splits.

So two trees trained on slightly different samples can differ noticeably.

Two panels with the same cloud of points: on the left one point is ringed and the cloud is split by a vertical line, on the right the same point is shifted right and the cloud is split by a horizontal line; below each panel a small tree with a different condition in its root
The instability of a tree. Both panels contain almost the same points; only one point, ringed in amber, differs — in the right panel it is shifted to the right. Because of that the tree chooses a completely different first condition: on the left a vertical boundary and the question x1 ≤ 3, on the right a horizontal boundary and the question x2 ≤ 5. A tiny change in the data — and the structure of the tree is different.

2. The risk of overfitting.

A deep tree can memorize individual training examples. Complexity constraints and pruning help reduce this risk.

3. Step-like predictions.

In a regression tree the objects of one leaf receive the same prediction. This can be inconvenient if the real dependence changes smoothly.

4. Local greediness. At each step the tree chooses the best split by the current criterion, but it does not guarantee a globally optimal structure.

5. Limited stability of a single tree.

A single tree can depend strongly on the composition of the training sample. There are ensemble methods that combine many trees in order to obtain more stable predictions. We will study them in the following lectures.

12. Trees and other models

Let us bring the models we already know together in one table.

Characteristic Linear regression Logistic regression KNN SVM Decision tree
Main task Regression Classification Classification and regression Usually classification; regression variants exist Classification and regression
Principle A weighted sum of features A probabilistic transformation of a linear combination of features Similarity to the nearest objects A separating boundary A sequence of conditions
Non-linear dependencies Not in the basic linear form Not in the basic linear form Possible thanks to local neighbours Possible with suitable kernels Possible thanks to successive splits
Scaling May be useful, depends on the task and the training method May be useful Usually important Often important Usually not required
Interpretability The coefficients can be interpreted with caveats The coefficients and probabilities can be interpreted with caveats A prediction can be explained through the neighbours The interpretation depends on the model and the features Often convenient to explain through rules
Main limitation Does not always describe a complex non-linear dependence A linear boundary in the basic variant Dependence on distances and the data The choice of parameters and the boundary Overfitting and instability of the structure

The main difference: a tree does not compute a single common linear prediction and does not look for neighbours. It divides the feature space into regions using successive conditions.

Two panels with the same arrangement of points of two classes: on the left a diagonal straight line that fails to separate the classes, with four ringed points; on the right the plane cut into four coloured rectangles matching the classes
A tree and a linear model on the same data. The points of the two classes form a checkerboard. On the left a single straight line ("linear model") cannot separate them: four objects are ringed because they end up on the wrong side. On the right the tree ("decision tree") cuts the plane into four rectangles, and each one contains only its own points. Where a combination of conditions is needed instead of one slanted boundary, the tree wins.

13. Typical mistakes and misconceptions

Mistake 1. "A tree simply asks random questions."

Incorrect. In standard training a tree compares admissible splits by the chosen criterion and selects the most suitable among the candidates considered.

Mistake 2. "The deepest tree is always the best."

Incorrect. Greater depth increases flexibility, but it can lead to overfitting. Quality should be evaluated on data that was not used for training.

Mistake 3. "If a tree makes no mistakes on the training set, then it is good." Incorrect. It may have memorized the training examples. It is important to check how well it performs on new objects.

Mistake 4. "Entropy and the Gini index are the same thing."

They measure a similar property, but they use different formulas. The values differ, although both measures equal zero in a pure node.

Mistake 5. "The splitting criterion and the model's quality metric are the same thing."

Not necessarily. The splitting criterion is used to choose conditions inside the tree. A quality metric evaluates the predictions, for example on a validation set. These quantities can be related, but they solve different problems.

Mistake 6. "Trees always need their features normalized."

Usually they do not. Standard trees make decisions on the basis of the order of values and thresholds. The scaling that matters for KNN and SVM is usually not required.

Mistake 7. "A regression tree predicts only classes." Incorrect. A regression tree predicts numerical values, for example a price or a delivery time.

Mistake 8. "Greedy selection guarantees a globally optimal tree." Incorrect. At each step the best split by the local criterion is chosen. This does not guarantee the best tree structure overall.

Mistake 9. "If a split creates groups of equal size, it is necessarily better." Incorrect. The size of the groups is not a goal in itself. What matters is how much the split reduces the impurity or the error.

Mistake 10. "One feature cannot be used twice." Incorrect. A tree can test one feature in different nodes, refining the conditions inside the child groups.

14. Preparing for an ML interview

Below are questions from basic to more complex. First a short answer is given that you can say at an interview. Then a clarification that helps you understand the material more deeply.

Basic questions

1. What is a decision tree?

Short answer: a decision tree is a machine-learning model that successively tests conditions on features and produces a prediction in a final leaf.

In more detail: a tree consists of a root, internal nodes, branches and leaves. The internal nodes contain conditions, and the leaves contain predictions of classes or numerical values.

2. What tasks do decision trees solve?

Short answer: classification and regression.

In more detail: a classification tree predicts a category, and a regression tree predicts a numerical value. Their structural principle is similar, but the splitting criteria and the contents of the leaves differ.

3. What are the root and a leaf of a tree?

Short answer: the root is the initial node, and a leaf is a final node with a prediction.

In more detail: an object travels from the root along the branches determined by the values of its features until it reaches a leaf.

4. What is a split?

Short answer: a split divides the objects of the current node into groups by a condition.

In more detail: for example, the condition "age is not greater than 30" can send some objects to the left branch and the rest to the right. A good split strives to make the resulting groups more homogeneous with respect to the target variable.

5. How is a tree trained?

Short answer: it chooses good splits, repeats the process in the child nodes and stops when the stopping conditions are met.

In more detail: standard algorithms often use a greedy search: at each step they choose the best available option by a certain criterion, without enumerating all possible trees.

6. What is a greedy algorithm?

Short answer: an algorithm that chooses the best decision at the current step without guaranteeing a globally optimal result. In more detail: in a tree it chooses a split of the current node and then solves the problems for the child nodes separately.

Questions about the mathematics

7. What is the impurity of a node?

Short answer: it is a measure of how mixed the classes in a node are.

In more detail: if a node contains one class, the impurity is zero. Entropy and the Gini index allow the mixedness of several classes to be estimated numerically.

8. What is entropy?

Short answer: entropy measures the uncertainty of the class distribution in a node. In more detail: for classes with shares \(p_k\) it is calculated by the formula:

\[ H(S)=-\sum_k p_k\log_2p_k. \]

For a pure node the entropy is zero. For two classes represented in equal shares it reaches one.

9. What is the Gini index?

Short answer: the Gini index is a measure of class impurity, computed as one minus the sum of the squared class shares. In more detail:

\[ G(S)=1-\sum_kp_k^2. \]

For a pure node the index is zero. For two equal classes it is \(0.5\).

10. How does entropy differ from the Gini index?

Short answer: both measures estimate impurity, but they use different mathematical functions.

In more detail: their numerical values differ, but both equal zero for a pure node and grow as the classes become more mixed. The specific criterion is chosen by the tree implementation.

11. What is information gain?

Short answer: it is the reduction in entropy after a split. In more detail:

\[ IG=H_{\text{before}}-H_{\text{after}}. \]

The entropy after the split is the weighted sum of the entropies of the child nodes. The greater the information gain, the more the split reduced the entropy.

12. Why are child nodes weighted by the number of objects?

Short answer: so that the size of each group is taken into account when evaluating the overall quality of the split.

In more detail: a node with a large number of objects should make a larger contribution to the average impurity. A simple average of the entropies without weights can distort the estimate.

Questions about regression and complexity

13. How does a regression tree work?

Short answer: it divides the objects by features and predicts a numerical value in each leaf.

In more detail: when the squared error is used, the mean of the target values in the leaf is often taken. The splits are chosen so as to reduce the sum of squared deviations.

14. Why does a tree overfit?

Short answer: a tree that is too complex can memorize individual training examples instead of general patterns.

In more detail: this increases the risk of worse quality on new objects. Limits on depth and minimum node size, as well as pruning, help control complexity.

15. How is the complexity of a tree controlled?

Short answer: by limiting the depth, the minimum node size and the number of leaves, and by applying pruning.

In more detail: parameters such as max_depth and min_samples_leaf limit growth in advance. Post-pruning makes it possible to simplify a tree that has already been built.

16. What are pre-pruning and post-pruning?

Short answer: pre-pruning stops growth, and post-pruning simplifies a tree that has already been built.

In more detail: pre-pruning saves computation but can stop a useful split. Post-pruning makes it possible to build a more complex structure first and then remove the least useful branches.

17. How does a tree handle numerical features?

Short answer: it tests conditions relative to a threshold, for example \(x_j\le t\).

In more detail: candidate thresholds are often chosen between adjacent distinct values of the feature. Then the split that is better by the chosen criterion is selected.

18. Why do trees usually not require scaling?

Short answer: because the splits are based on comparisons of feature values with a threshold, not on distances between objects.

In more detail: an ordinary change of scale that preserves the order of values usually preserves equivalent ways of separating the training objects.

19. Why are trees sensitive to changes in the data?

Short answer: a change in the first split changes the composition of the child nodes and can affect all subsequent decisions.

In more detail: a tree is built successively, and local decisions affect the structure of the subtrees. That is why small changes in the training sample can noticeably change the final model.

20. What are the main advantages and disadvantages of a single tree?

Short answer: trees are interpretable, can model non-linear dependencies and usually do not require scaling, but they can overfit and be unstable.

In more detail: their greedy construction is efficient, but it does not guarantee a global optimum. Quality depends on the data, the splitting criterion and the complexity constraints.

15. Tasks for independent solution

First try to solve the tasks without hints. There is no need to hurry here: the goal is to learn to choose the formula yourself, substitute the values and explain the result.

Block A. Tree structure

1. Path to a leaf

Given the tree:

```
             Age ≤ 30?
           /          \
         Yes            No
         |               |
  Been on the site?   "Won't buy"
      /     \
    Yes      No
    |         |
"Will buy"  "Won't buy"
```

Determine the prediction for three visitors:

  1. Age 25, has visited the site before.
  2. Age 25, has not visited the site before.
  3. Age 45, has visited the site before.

2. Counting the nodes

Given a full binary tree with four internal nodes.

How many leaves does it have and how many nodes in total?

3. Depth

The root has depth 0. It is followed by two nodes of depth 1. One of these nodes has two children of depth 2, and one of them has a child of depth 3.

What is the maximum depth of the tree? How many edges does an object traverse if its path ends in a node of depth 3?

Block B. Entropy and the Gini index

For the calculations use the formulas:

\[ H=-\sum_k p_k\log_2p_k, \qquad G=1-\sum_kp_k^2. \]

4. A pure node

A node contains 12 objects, and all of them belong to class A.

Compute the entropy and the Gini index.

5. Two equal classes

A node contains 8 objects of class A and 8 objects of class B.

Compute the entropy and the Gini index.

6. Unequal classes

A node contains 6 objects of class A and 2 objects of class B.

Compute the class shares, the entropy and the Gini index. Compare the result with task 5.

Block C. Comparing splits

7. Which split is better?

The original node contains 10 objects: 5 objects of class A and 5 of class B.

Two options are considered.

  • Split A: two child nodes contain 5 objects of one class each.
  • Split B: both child nodes contain 5 objects, of which 3 are of class A and 2 of class B.

For each option compute the weighted entropy and the information gain. Which split is better?

8. Why are weights needed?

The original node contains 10 objects.

After the split:

  • the first node has 9 objects and its entropy is 0;
  • the second node has 1 object and its entropy is 1.

Compute the weighted entropy after the split and compare it with the ordinary average of the two entropies. Explain why the results differ.

Block D. Regression tree

9. The prediction in a leaf

Three objects with the target values 10, 12 and 14 ended up in a leaf.

Find the mean value that will be the prediction when the squared error is used. Then compute the SSE.

10. Improving a split

There are four objects with the target values:

\[ 2,\ 4,\ 10,\ 12. \]

First they are all in one leaf. Then the tree divides them into the groups \((2,4)\) and \((10,12)\).

Compute the mean and the SSE before the split, then the means and the total SSE after the split. By how much did the error decrease?

Block E. Overfitting

11. Choosing the depth

The conventional errors of two trees are given:

Tree Training error Error on new data
A 0.12 0.15
B 0.02 0.27

Which tree generalizes the data better? Why can a model not be chosen by the training error alone?

12. Choosing a constraint

A node contains only 7 objects. The tree has min_samples_split = 8 set.

Can a standard implementation that respects this parameter split this node? How will the answer change if min_samples_split = 5 is set, provided that the remaining constraints and criteria allow the split to be performed?

Show detailed solutions

1. Path to a leaf

  1. Age 25: the condition "age is not greater than 30" is true. The visitor has been on the site before, so it reaches the leaf "Will buy".
  2. Age 25: we take the same first branch. But the visitor has not been on the site before, so it reaches the leaf "Won't buy".
  3. Age 45: the condition is false. We go straight to the right leaf "Won't buy". The previous-visit feature is not tested here.

2. Counting the nodes

For a full binary tree:

\[ L=I+1. \]

The number of internal nodes is \(I=4\).

\[ L=4+1=5. \]

Total nodes:

\[ N_{\text{nodes}}=I+L=4+5=9. \]

Answer: 5 leaves and 9 nodes.

3. Depth

The maximum depth is 3. Since the root has depth 0, the path to a node of depth 3 contains three transitions, that is, three edges.

4. A pure node

All 12 objects belong to class A:

\[ p_A=1,\qquad p_B=0. \]

Entropy:

\[ H=-(1\log_2 1+0\log_2 0)=0. \]

Gini index:

\[ G=1-(1^2+0^2)=0. \]

Answer: both measures equal zero.

5. Two equal classes

There are 16 objects in total:

\[ p_A=p_B=\frac8{16}=0.5. \]

Entropy:

\[ H=-\left(0.5\log_2 0.5+ 0.5\log_2 0.5\right)=1. \]

Gini index:

\[ G=1-(0.5^2+0.5^2) =1-0.5=0.5. \]

Answer: the entropy equals 1 and the Gini index equals 0.5.

6. Unequal classes

There are 8 objects in total:

\[ p_A=\frac68=0.75,\qquad p_B=\frac28=0.25. \]

Entropy:

\[ H=-\left( 0.75\log_2 0.75+ 0.25\log_2 0.25 \right). \]

Using approximate logarithms:

\[ H\approx-(-0.311-0.5)=0.811. \]

Gini index:

\[ G=1-(0.75^2+0.25^2). \]
\[ G=1-(0.5625+0.0625)=0.375. \]

Comparison with task 5:

  • the entropy decreased from 1 to approximately 0.811;
  • the Gini index decreased from 0.5 to 0.375.

The node has become more homogeneous, because class A now predominates.

7. Which split is better?

The original entropy:

\[ H_{\text{before}}=1. \]

Split A. Both child nodes are pure:

\[ H_{\text{after,A}}= \frac5{10}\cdot0+\frac5{10}\cdot0=0. \]
\[ IG_A=1-0=1. \]

Split B. Each node has three objects of class A and two of class B. The shares:

\[ p_A=\frac35=0.6,\qquad p_B=\frac25=0.4. \]

The entropy of each node:

\[ H=-\left(0.6\log_2 0.6+ 0.4\log_2 0.4\right) \approx0.971. \]

Both nodes have the same composition, so the weighted entropy is also approximately 0.971:

\[ IG_B=1-0.971=0.029. \]

Comparison:

Option Entropy after the split Information gain
A 0 1
B ≈ 0.971 ≈ 0.029

Split A is considerably better: it separates the classes completely.

8. Why are weights needed?

The weighted entropy:

\[ H_{\text{after}}= \frac9{10}\cdot0+\frac1{10}\cdot1=0.1. \]

The ordinary average:

\[ \frac{0+1}{2}=0.5. \]

Why do the results differ? The ordinary average gives both nodes the same weight, even though one contains 9 objects and the other only 1.

The weighted estimate takes the contribution of all ten objects in the corresponding groups into account.

9. The prediction in a leaf

The target values:

\[ 10,\ 12,\ 14. \]

The mean:

\[ \bar y=\frac{10+12+14}{3} =\frac{36}{3}=12. \]

The prediction is 12. SSE:

\[ SSE=(10-12)^2+(12-12)^2+(14-12)^2. \]
\[ SSE=4+0+4=8. \]

Answer: the prediction is 12 and the SSE equals 8.

10. Improving a split

Before the split, the mean of the four values:

\[ \bar y=\frac{2+4+10+12}{4} =\frac{28}{4}=7. \]

SSE before the split:

\[ SSE_{\text{before}}=(2-7)^2+(4-7)^2+ (10-7)^2+(12-7)^2. \]
\[ SSE_{\text{before}}=25+9+9+25=68. \]

After the split the first group contains 2 and 4:

\[ \bar y_L=\frac{2+4}{2}=3. \]
\[ SSE_L=(2-3)^2+(4-3)^2=1+1=2. \]

The second group contains 10 and 12:

\[ \bar y_R=\frac{10+12}{2}=11. \]
\[ SSE_R=(10-11)^2+(12-11)^2=1+1=2. \]

The total error:

\[ SSE_{\text{after}}=2+2=4. \]

The reduction:

\[ \Delta SSE=68-4=64. \]

The split substantially reduced the error, because the values inside each group became much closer to each other.

11. Choosing the depth

Tree A has an error of 0.15 on new data, and tree B has 0.27. By this indicator tree A is better.

Tree B has a considerably lower training error, but that does not mean it is better. It may have fitted the training sample too closely.

12. Choosing a constraint

With min_samples_split = 8 a node of 7 objects cannot be split, because there are fewer objects than the set minimum.

If min_samples_split = 5 is set, then by this constraint the split becomes admissible. But it will happen only if the other constraints and criteria also allow it to be performed.

16. Glossary of terms

Term Simple explanation Where it is used
Decision Tree A model that makes decisions by a sequence of conditions Classification and regression
Root The initial node of the tree The start of an object's path
Node An element of the tree structure Storing a condition or a prediction
Internal node A node from which branches go out Testing conditions
Leaf A final node with a prediction Producing the result
Branch A transition between nodes The direction of an object through the tree
Split Dividing objects into groups Training the tree
Threshold A number to compare with a feature value Splitting by a numerical feature
Feature A characteristic of an object The input data of the model
Target The correct answer to be predicted Supervised learning
Impurity A measure of how mixed the classes are Classification trees
Entropy A measure of the uncertainty of the class distribution Choosing splits
Gini impurity An alternative measure of class impurity Choosing splits
Classification error The share of objects not belonging to the most numerous class Estimating impurity
Information Gain The reduction in entropy after a split Choosing a condition
Impurity reduction The difference between the impurity before and after a split Evaluating splits
Recursive partitioning Successively dividing groups into smaller groups Building the tree
Greedy algorithm Choosing the best option at the current step Training the tree
Classification tree A tree that predicts classes Classification
Regression tree A tree that predicts numbers Regression
Overfitting Excessive fitting to the training data Quality control
Generalization The ability to work on new data Model evaluation
Pruning Simplifying a tree Complexity control
Pre-pruning Limiting the growth of a tree Training
Post-pruning Simplifying a tree that has already been built Training and tuning
max_depth The maximum length of a path through the tree Complexity control
min_samples_split The minimum number of objects for a split Complexity control
min_samples_leaf The minimum number of objects in a leaf Complexity control
max_leaf_nodes The maximum number of leaves Complexity control
SSE The sum of squared errors Regression trees
MSE The mean squared error Evaluating regression predictions
Binary split Dividing a node into two groups Many tree implementations

17. Final summary

17.1. Topic map

  1. Data and the task

    Objects with features; the goal is to predict a class or a number.

  2. A sequence of conditions

    The tree tests a feature and leads the object along a branch: \(x_j \le t\) goes left, otherwise right.

  3. Splitting a node

    Among the admissible conditions, the one that makes the child groups more homogeneous is chosen.

  4. Classification impurity

    \[ H(S)=-\sum_{k=1}^{K}p_k\log_2 p_k, \qquad G(S)=1-\sum_{k=1}^{K}p_k^2. \]
  5. Information gain

    \[ IG=H_{\text{before}}-H_{\text{after}}. \]
  6. The prediction in a leaf for regression

    \[ \bar y=\frac1N\sum_{i=1}^{N}y_i. \]
  7. Splitting error

    \[ SSE=\sum_{i=1}^{N}(y_i-\bar y)^2, \qquad \Delta SSE=SSE_{\text{before}}-SSE_{\text{after}}. \]
  8. Complexity control

    max_depth, min_samples_split, min_samples_leaf and pruning.

  9. A ready tree

    A new object goes from the root to a leaf and gets a prediction.

17.2. Concept → what it means → why it is needed

Concept What it means Why it is needed
Root The first node The start of decision making
Internal node Testing a condition Choosing the next step
Leaf A final node Producing the prediction
Split Dividing objects Finding groups with similar targets
Entropy Uncertainty of the classes Estimating mixedness
Gini index Impurity of the classes An alternative estimate of mixedness
Information gain Reduction in entropy Comparing splits
SSE The sum of squared deviations Estimating the spread of numerical targets
Greedy algorithm The best local choice Efficient construction of the tree
Overfitting Fitting the training data Explains the drop in quality on new objects
Pruning Simplifying a tree Complexity control
Validation set Data for evaluating the model Checking generalization

17.3. A sheet of the main formulas

Class share

\[ p_k=\frac{n_k}{N}. \]
  • \(n_k\) — the number of objects of class \(k\);
  • \(N\) — the number of objects in the node.

Entropy

\[ H(S)=-\sum_{k=1}^{K}p_k\log_2p_k. \]

It measures the uncertainty of the class distribution.

Gini index

\[ G(S)=1-\sum_{k=1}^{K}p_k^2. \]

It measures the impurity of the classes.

Classification error in a node

\[ E(S)=1-\max_k p_k. \]

It measures the share of objects that do not belong to the most numerous class.

Weighted entropy after a split

\[ H_{\text{after}} =\frac{N_L}{N}H(L)+\frac{N_R}{N}H(R). \]

It takes the impurity of both groups and their sizes into account.

Information gain

\[ IG=H_{\text{before}}-H_{\text{after}}. \]

It shows by how much the split reduced the entropy.

The mean value in a regression leaf

\[ \bar y=\frac1N\sum_{i=1}^{N}y_i. \]

It is used as the prediction when the sum of squared deviations is minimized.

The sum of squared errors

\[ SSE=\sum_{i=1}^{N}(y_i-\bar y)^2. \]

It shows the overall spread of the target values around the mean in a node.

The reduction in the sum of squared errors

\[ \Delta SSE=SSE_{\text{before}}-SSE_{\text{after}}. \]

It allows the splits of a regression tree to be compared.

17.4. Ten main ideas

  1. A decision tree predicts a result by means of a sequence of conditions on features.
  2. The root starts the path, the internal nodes test conditions, and the leaves produce the prediction.
  3. A good split strives to make the child groups more homogeneous with respect to the target variable.
  4. For classification, entropy and the Gini index are often used.
  5. A pure node has zero entropy and a zero Gini index.
  6. Information gain equals the reduction in entropy after a split; when it is computed, the child nodes are weighted by the number of objects.
  7. A regression tree predicts numbers, often using the mean of the target values in the leaf.
  8. A greedy algorithm chooses the best available split at the current step, but it does not guarantee a globally optimal tree.
  9. A tree that is too deep can overfit, so complexity is controlled with constraints and pruning.
  10. It is important to evaluate the quality of a model on new data, not only on the training sample.

17.5. How to explain how a tree works at an interview

Here is a version of the answer that you can gradually master and retell in your own words:

A decision tree is a machine-learning model that builds a sequence of conditions on the features of an object. During training the algorithm considers possible splits and chooses those that separate the objects better with respect to the target variable. In classification, entropy or the Gini index is often used for this, and in regression, criteria connected with the reduction of the squared error. The construction is usually greedy and recursive: the chosen split is applied to the current node, and then the procedure is repeated in the child nodes. When a stopping criterion is reached, the leaves receive predictions. To keep the tree from overfitting, its depth or node sizes are limited, or pruning is applied. After training, a new object passes through the conditions from the root to a leaf and receives a prediction.

What is important to remember before the next lecture

Decision trees show how a model can learn from a sequence of understandable rules. The most important idea of this lecture is that the algorithm does not simply ask questions — it chooses them by a criterion of split quality.

For classification we worked through entropy, the Gini index and information gain. For regression we worked through the mean in a leaf and the sum of squared deviations. Finally, we saw that a tree must be complex enough to find useful patterns, but not so complex that it memorizes the training data.

You do not have to memorize all the formulas on the first reading. It is far more important to be able to explain what each of them measures, why the sizes of the groups are taken into account and how a change in the split affects the predictions.

The next stage of the course will continue the study of machine-learning methods in the established order. For now it is worth focusing on working through at least one task each on entropy, the comparison of splits and a regression tree. Those three skills are what will help consolidate the main logic of today's lecture.

Practice in the interactive lab

Three actions for this lecture: see what the decision boundary looks like, change the complexity of the model and explain how the error is measured.

  1. Look at the decision boundary — open "KNN: the K nearest neighbours": points on a plane and the boundary built by the training objects. A tree solves the same task differently: it cuts the space into regions with conditions of the form "the feature is not greater than a threshold", so its boundary is step-like and parallel to the coordinate axes.

  2. Change the complexity of the model — open "Polynomial degree: overfitting" and move the degree slider: with a small degree the model underfits, with a large one it overfits. The same happens with a tree when max_depth changes: a tree that is too shallow does not find the pattern, and one that is too deep memorizes the training data.

  3. Explain how the error is measured — open "Fit a line by hand": residuals, the sum of squared errors and how the position of the line changes the error. In a regression tree the leaf predicts the mean, and the quality of a split is measured by the reduction in the sum of squared errors — the same quantity.

There is no separate demo of decision trees in the lab: these three pages show related ideas, not the method itself.

Check yourself