1. Home
  2. Explore
  3. Computer Science
  4. Decision Trees and Random Forests

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Decision Trees and Random Forests

Decision Trees and Random Forests

Decision trees: purpose and applications

A decision tree is a tree-shaped model built from data. It makes predictions by applying a sequence of decisions about the input features. Each decision directs an observation along a branch until it reaches a final node, where the model gives a prediction.

Decision trees can be used for:

  • Classification: assigning an observation to one of a set of predefined classes.

  • Regression: predicting a numerical target value.

  • Function approximation: learning a relationship between input features and an output.

The same general tree structure can support both classification and regression. The way the tree chooses its splits differs depending on the task and the metric used to evaluate them.

At each step, the model considers how to divide the data into smaller groups. The aim is to create groups that are more useful for prediction than the group at the parent node.


How a decision tree represents data

Nodes, branches, and leaves

  • The root node is the starting point and contains all training observations.

  • An internal node applies a test to a feature, such as whether a feature value is below a threshold.

  • A branch represents one outcome of that test and leads to another node.

  • A leaf, or terminal node, is where the tree stops splitting and makes a prediction.

Each node contains the observations that satisfy all the decisions along the path from the root to that node. As the tree grows, its nodes usually contain progressively smaller subsets of the training data.

For example, a node might divide observations according to whether petal length is less than or equal to a chosen value. One group follows one branch; the other group follows the other branch.

Making a prediction

To classify a new observation, the model:

  1. Starts at the root.

  2. Checks the feature test at the current node.

  3. Follows the branch that matches the observation’s feature value.

  4. Repeats until it reaches a leaf.

  5. Uses the leaf’s class prediction.

For a regression tree, the same traversal process ends at a leaf that provides a numerical prediction.


Example: classifying Iris flowers

The Iris classification task predicts which of three species a flower belongs to:

  • Setosa

  • Versicolor

  • Virginica

Each flower is described by four measured features:

  • Sepal length

  • Sepal width

  • Petal length

  • Petal width

The training data contains labeled examples: each observation includes the four feature values and the species it belongs to. The tree uses those examples to learn rules for classifying flowers whose species are not known.

In the example, the training set contains 149149149 observations: 494949 setosa, 505050 versicolor, and 505050 virginica. The feature ranges differ across species, although they can overlap. A feature with clearly separated ranges can be especially useful for constructing a split.


Why the tree needs to split the data

If a model used only the root node and always predicted the most common class, it would make no use of the flower measurements. In this example, versicolor and virginica are tied as the most frequent classes, so the model would have to break the tie somehow. Predicting just one of them would correctly classify only about half the observations, while failing to identify the other classes well.

A tree attempts to improve on this baseline by dividing the training data into groups with more concentrated class membership. If a node contains observations from only one class, that node can make a clear classification.

However, the groups do not always become perfectly pure. Some feature values overlap across classes, so a split may leave multiple classes in a node. The model then predicts the majority class in that node, accepting that some observations may be misclassified.

The central idea is to use feature-based splits to create nodes that are more useful for prediction than the original, unsplit dataset.


Gini impurity for classification

Definition

Gini impurity measures how mixed the classes are within a node. For a node containing KKK classes, it is calculated as:

G=1−∑i=1Kfi2G = 1 - \sum_{i=1}^{K} f_i^2G=1−∑i=1K​fi2​

Here, fif_ifi​ is the fraction of observations in the node that belong to class iii.

  • A node containing only one class has Gini impurity 000.

  • A node containing several classes has a higher impurity.

  • Greater class balance generally means greater impurity.

Gini impurity can be calculated separately for every node in a tree.

Gini impurity at the Iris root

At the root, the class fractions are:

fsetosa=49149,fversicolor=50149,fvirginica=50149f_{\text{setosa}} = \frac{49}{149}, \qquad f_{\text{versicolor}} = \frac{50}{149}, \qquad f_{\text{virginica}} = \frac{50}{149}fsetosa​=14949​,fversicolor​=14950​,fvirginica​=14950​

Therefore, the root impurity is:

Groot=1−(49149)2−(50149)2−(50149)2≈0.667G_{\text{root}} = 1 - \left(\frac{49}{149}\right)^2 - \left(\frac{50}{149}\right)^2 - \left(\frac{50}{149}\right)^2 \approx 0.667Groot​=1−(14949​)2−(14950​)2−(14950​)2≈0.667

This value is relatively high because the root contains substantial numbers of observations from all three classes.

Gini impurity at a pure node

Suppose a node contains 505050 observations, all of which are versicolor. Its class fractions are 111, 000, and 000, so:

G=1−12−02−02=0G = 1 - 1^2 - 0^2 - 0^2 = 0G=1−12−02−02=0

A Gini impurity of zero indicates a pure node: every observation in it belongs to the same class.


Choosing a split with Gini impurity

Weighted impurity after a split

A candidate split divides a parent node into child nodes. The quality of the split depends on the impurity of both children and on how many observations go into each one.

For a split into two children, the weighted impurity after splitting is:

Gchildren=p1G1+p2G2G_{\text{children}} = p_1G_1 + p_2G_2Gchildren​=p1​G1​+p2​G2​

where:

  • G1G_1G1​ and G2G_2G2​ are the child nodes’ Gini impurities.

  • p1p_1p1​ and p2p_2p2​ are the fractions of the parent node’s observations that go to each child.

The Gini impurity reduction, also called the Gini gain in this explanation, is:

ΔG=Gparent−(p1G1+p2G2)\Delta G = G_{\text{parent}} - (p_1G_1 + p_2G_2)ΔG=Gparent​−(p1​G1​+p2​G2​)

A larger reduction indicates a more useful split: the weighted impurity of the children is lower relative to the parent. If a split produces perfectly pure children, their impurities are both zero and the reduction equals the parent’s impurity.

Example: splitting by petal length

Consider a candidate rule:

  • If petal length is less than 2.42.42.4, send the observation to one child.

  • Otherwise, send it to the other child.

In the training data, this split sends all 494949 setosa observations to one child and the remaining 100100100 observations—505050 versicolor and 505050 virginica—to the other.

The first child is pure, so its impurity is 000. The second child has equal fractions of versicolor and virginica:

Gsecond child=1−(50100)2−(50100)2=0.5G_{\text{second child}} = 1 - \left(\frac{50}{100}\right)^2 - \left(\frac{50}{100}\right)^2 = 0.5Gsecond child​=1−(10050​)2−(10050​)2=0.5

The children’s weighted impurity is:

49149(0)+100149(0.5)≈0.336\frac{49}{149}(0) + \frac{100}{149}(0.5) \approx 0.33614949​(0)+149100​(0.5)≈0.336

The corresponding impurity reduction is approximately:

0.667−0.336≈0.3310.667 - 0.336 \approx 0.3310.667−0.336≈0.331

This split cleanly separates setosa from the other species, but it does not separate versicolor from virginica.

Comparing candidate splits

A decision-tree algorithm considers candidate features and threshold values, evaluates their splits, and selects a promising one. For instance, it can compare:

  • A split based on sepal length at a chosen threshold.

  • A split based on petal length at another threshold.

  • A split based on sepal width or petal width.

The chosen feature and threshold determine which observations enter each child. The split’s score then reflects how much the class composition improves.

The algorithm automates this search. Understanding the impurity and split calculations helps explain why a particular feature and threshold appear in the final tree.


Growing the tree

After a split, each child node can be considered for further splitting. A child that is already pure needs no further division for classification. A mixed child may be split again using another feature or a new threshold.

For the Iris example, a second split can separate the non-setosa observations using petal width. A simplified tree might apply:

  1. If petal length is less than or equal to 2.42.42.4, predict setosa.

  2. Otherwise, check petal width:

    • If petal width is less than 1.81.81.8, predict versicolor.

    • Otherwise, predict virginica.

The numbers illustrate how the rules work; the resulting branches can still contain classification errors. In the training example, the second split sends about 545454 observations to one child and 464646 to the other, with each child named after its majority class.

The full tree is built through successive decisions. Each new split subdivides an existing node’s observations, and the process continues until the algorithm’s stopping conditions are met.


Imperfect splits, errors, and overfitting

Overlapping data

A dataset may not allow perfect separation. If feature ranges overlap, no single threshold can divide the classes without placing some observations together. Further splits may reduce the errors, but they may not eliminate them.

At a mixed leaf, the tree generally predicts the majority class among the observations in that leaf. This gives the most common training class for that region of feature space, but it does not guarantee a correct prediction for every new observation.

Training performance versus generalization

A tree can often reduce training errors by continuing to grow and creating more specific rules. If it becomes very deep, it may memorize irregularities or noise in the training set. This is overfitting: the model fits the training observations closely but may perform poorly on new data.

A tree that separates every training example perfectly is not necessarily a good model. A more complex tree may have less ability to generalize—to make accurate predictions for observations not seen during training.

For this reason, tree growth may be stopped before every node becomes pure. A model can accept some training errors in exchange for a simpler tree that performs better on unseen data. Performance should be evaluated using data not used to fit the tree, such as a test set.


Decision trees for regression

A regression tree predicts a numerical target rather than a class label. At a node, a simple baseline prediction could be the average target value of all observations in that node. As with classification, this baseline may be too crude if the node contains observations with substantially different target values.

Regression trees divide the data into smaller groups so that observations within each group have more similar target values. Variance reduction is a common criterion for deciding whether a split improves a regression tree.

The general idea parallels classification:

  • Classification uses class impurity, such as Gini impurity.

  • Regression uses variation in numerical target values.

  • In either task, the tree selects feature-based splits intended to make its predictions more useful.


Other split metrics

Gini impurity is one way to guide classification splits, but it is not the only one.

  • Information entropy is another classification metric. It measures uncertainty about class membership and can be used to evaluate how much a split reduces that uncertainty.

  • Variance reduction is commonly used for regression, where the goal is to create groups with less variation in their target values.

Different software packages may offer different tree-building algorithms and split criteria. Although the metrics differ mathematically, they serve a related purpose: they help the algorithm choose how to divide a node’s data.


Random forests

Why use multiple trees?

A decision tree can be sensitive to changes in its training data. A small change in the observations may lead to a different feature or threshold being selected, which can produce a substantially different tree. This sensitivity makes a single tree less robust to fluctuations or errors in the data.

A random forest addresses this issue by combining predictions from multiple decision trees rather than relying on just one.

Building a forest

A random forest creates several training sets or variations of the original data, builds a tree for each, and combines the trees’ predictions. The variations can be created by:

  • Selecting different subsets of observations.

  • Selecting different subsets of features.

  • Using combinations of these approaches.

A common approach uses resampling of observations and random feature subsets to encourage the trees to differ. This process is related to bagging—building models on varied samples and aggregating their predictions.

For example, one tree might use sepal length, sepal width, and petal length, while another might use only sepal length and petal length. Each tree learns its own decision rules from the information available to it.

Combining predictions

For a classification task, each tree predicts a class. The random forest returns the class receiving the most votes:

  • If most trees predict setosa, the forest predicts setosa.

  • If two trees predict setosa and one predicts virginica, the majority prediction is setosa.

  • If the votes are tied, the implementation needs a rule to break the tie.

For regression, the trees’ numerical predictions are commonly combined by averaging.

Why the forest can be more robust

Because each tree is built from a different view of the data, the trees do not all respond identically to every fluctuation. Combining their outputs reduces dependence on the quirks of a single tree. When many trees agree, their shared prediction can be more reliable than a prediction from one potentially unstable tree.

A random forest is therefore not one large decision tree. It is an ensemble of trees whose predictions are aggregated.


Key distinctions

Decision tree

  • A single tree applies a sequence of feature-based rules.

  • It can be interpreted by tracing a path from root to leaf.

  • It may be sensitive to changes in the training data.

  • Its predictions come from the terminal node reached by the observation.

Random forest

  • A collection of decision trees is trained using varied data or feature selections.

  • Classification predictions are combined by voting; regression predictions are commonly averaged.

  • Combining trees can reduce sensitivity to changes in the training data.

  • Its overall prediction is aggregated across the forest rather than taken from one tree alone.

A decision tree provides an interpretable sequence of decisions, while a random forest uses agreement among multiple trees to produce a more robust prediction.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent