Skip to main content
LearnMLAcademy
Intermediate10 min read

Decision Trees

Construct decision tree classifiers with Gini impurity and cost pruning, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Decision Tree

Decision Trees are algorithms that work by repeatedly asking questions about the data and splitting it into smaller groups until a final prediction is made.

Decision Tree in Simple Words

Think of a Decision Tree as a sequence of simple questions. Each answer sends us to the next question until we reach a final decision.

Simple Example: Should We Play Cricket?

Is it raining?

No ↓

Play outside

Yes ↓

Indoor ground available?
Yes → Play inside
No → Do not play

1. Ask

Ask one useful question about a feature.

2. Split

Send different answers into different groups.

3. Predict

Keep asking until the tree reaches a final prediction.

A Decision Tree looks similar to a flowchart:

  • Each internal node represents a question
  • Each branch represents an answer
  • Each leaf node represents the final prediction

Decision Trees are widely used because their rules are easy to inspect, they can model nonlinear relationships, and the same tree idea can be used for both classification and regression.


What is a Decision Tree?

A Decision Tree is a supervised machine learning algorithm that divides data into smaller subsets based on conditions. The model learns a sequence of decision rules from historical data and uses those rules to make predictions on new data.

Figure 3 — Decision Tree: Loan Approval (Root → Internal Nodes → Leaf Predictions)
No (≤30)Yes (>30)NoYesNoYesAge > 30?Decision nodeIncome > 50k?Decision nodeCredit > 700?Decision node✗ Reject✓ Approve✗ Reject✓ ApproveRoot Node splits on the most informative feature (highest Information Gain / lowest Gini Impurity)

Simple Decision Tree Workflow

Input Data↓Ask Questions↓Split Dataset↓Create Smaller Groups↓Final Prediction

Real-Life Example: Bank Loan

Suppose a bank wants to decide whether to approve a loan. The tree learns rules automatically from previous customer records.

Is Salary > 50,000?
NO
YES
REJECT LOAN
Is Credit Good?
REJECT
APPROVE

Structure of a Decision Tree

A Decision Tree mainly contains three types of nodes, forming a hierarchical structure.

1. Root Node

Topmost node containing the training samples before the first split. The algorithm searches possible feature-and-threshold splits and chooses one according to its splitting criterion.

Example:
Is Age > 30?

2. Decision Node

Internal nodes where additional conditions are evaluated to divide dataset into smaller, purer groups.

Example:
Is Income > 60K?

3. Leaf Node

Represents the final prediction for samples that reach that node. A leaf does not have to be perfectly pure; tree-stopping rules may end splitting earlier.

Example:
Loan Approved

Types of Decision Trees

Classification Tree

Predicts discrete categories or labels.

Examples

  • YES / NO
  • SPAM / NOT SPAM
  • FRAUD / LEGITIMATE

Applications

  • Spam detection
  • Medical diagnosis
  • Customer churn

Regression Tree

Predicts continuous numerical values.

Examples

  • House Price
  • Temperature
  • Sales Forecast

Applications

  • Real estate pricing
  • Demand forecasting
  • Revenue estimation

How Decision Trees Work & Purity

The main objective is to repeatedly divide the dataset into smaller and purer groups. At each node, the algorithm compares possible questions and chooses a split that improves the chosen impurity or prediction-loss criterion the most.

See the Goal Before the Formula

Before a useful split

YES · NO · YES · NO · YES · NO

Classes are mixed together.

→

YES · YES · YES

NO · NO · NO

Better split → purer child groups

Understanding Purity

Pure Node Example
YESYESYESYES

All samples belong to the same category.

Impure Node Example
YESNOYESNO

The node contains mixed categories.


Splitting Criteria (Math)

A classification tree needs a mathematical method to compare possible splits. Two common classification criteria are Gini impurity and Entropy / Information Gain.

Regression tree note: when the target is a number, the tree usually compares splits using a regression loss such as squared error rather than class impurity.

1. Gini Index

Measures how mixed the classes are inside a classification node. Lower values mean greater purity. Scikit-learn uses Gini impurity as the default classification criterion. The formula is:

Gini = 1 - Σ(pᵢ²)

Where pᵢ = probability of class i

Gini ValueInterpretation
0Perfectly pure node
0.5Most mixed binary node (50/50)

For more than two classes, the maximum possible Gini impurity is higher than 0.5 and depends on the number of classes.

Worked Example of Gini Index

Suppose a node contains 6 YES and 4 NO (Total: 10)

Step 1: ProbabilitiesP(YES) = 6/10 = 0.6
P(NO) = 4/10 = 0.4
Step 2: Apply FormulaGini = 1 - (0.6² + 0.4²)
Gini = 1 - (0.36 + 0.16)
Gini = 1 - 0.52 = 0.48

For a binary node, 0.48 is close to the maximum of 0.5, so the classes are still highly mixed.

2. Entropy & Information Gain

Entropy measures disorder or uncertainty inside a node (from Information Theory). Lower entropy means more organized data. Information Gain measures how much Entropy decreases after a split.

Entropy = -Σ(pᵢ * log₂(pᵢ))
Gain = Entropy(Parent) - Weighted_Entropy(Children)
ValueMeaningGoal
0Perfectly pureMinimize
1Max disorder (binary)
High GainHuge uncertainty dropMaximize

Worked Example of Entropy

Suppose a node contains 6 YES and 4 NO (Total: 10)

Calculation StepsP(YES) = 0.6, P(NO) = 0.4
log₂(0.6) ≈ -0.737, log₂(0.4) ≈ -1.322
Multiply Values0.6 * -0.737 = -0.4422
0.4 * -1.322 = -0.5288
Entropy = -(-0.4422 - 0.5288) = 0.971

For two classes, entropy 0.971 is close to the maximum of 1, so the node is highly mixed.

Tiny Information Gain Example

Suppose a question splits the 10 samples into a pure child with 4 YES samples and another child with 2 YES + 4 NO samples.

Step 1: Parent entropy = 0.971

Step 2: Child entropies ≈ 0 and 0.918

Step 3: Weighted child entropy = (4/10 × 0) + (6/10 × 0.918) ≈ 0.551

Step 4: Information Gain = 0.971 − 0.551 ≈ 0.420

The question reduced uncertainty by about 0.420 in this small example.


Advanced: Overfitting & Limitations

Overfitting

Decision Trees can grow very deep and fit details that do not generalize well. This is overfitting: training performance may look strong while performance on new data gets worse.

  • Creates very deep, complex branches
  • Captures noise and outliers
  • Leads to poor test accuracy

Pruning (One Control Strategy)

Tree complexity can be controlled while growing the tree or by pruning branches afterward. The goal is to keep useful structure without fitting unnecessary detail.

  • Control growth: use settings such as max_depth, min_samples_split, or min_samples_leaf.
  • Post-pruning: cost-complexity pruning can remove branches using a parameter such as ccp_alpha.

Advantages vs Disadvantages

✅ Advantages❌ Disadvantages
Interpretable: Human-readable rulesOverfitting: Deep trees can fit noise and overly specific patterns
Scaling usually unnecessary: splits rely on feature thresholds rather than distancesInstability: Small data changes can sometimes produce a noticeably different tree
Handles nonlinear relationships nativelyGreedy splitting: Each split is chosen locally, so the final tree is not guaranteed to be globally optimal

Python Implementation

Here is a practical Python implementation using Scikit-Learn.

python

Interactive: Train a Decision Tree in Python

Tune the maximum depth and splitting criterion to inspect how the tree structure and decision rules change in real-time.

Live Hyperparameters (Tweak & Re-run)
3
14

Limits how many levels of conditional splits the tree can grow.

gini

Mathematical metric used to evaluate the purity of candidate splits.

1import pandas as pd
2from sklearn.model_selection import train_test_split
3from sklearn.tree import DecisionTreeClassifier, export_text
4from sklearn.metrics import accuracy_score
5
6# 1. Dataset
7data = {
8 "Age": [22, 25, 28, 31, 35, 38, 42, 45, 48, 52, 55, 60],
9 "Income": [18000, 22000, 30000, 35000, 42000, 50000, 58000, 65000, 72000, 80000, 90000, 100000],
10 "Buy": [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
11}
12df = pd.DataFrame(data)
13X = df[["Age", "Income"]]
14y = df["Buy"]
15
16# 2. Train-Test Split
17X_train, X_test, y_train, y_test = train_test_split(
18 X, y, test_size=0.33, random_state=42, stratify=y
19)
20
21# 3. Train Decision Tree
22max_depth = 3
23criterion = 'gini'
24model = DecisionTreeClassifier(max_depth=3
25model.fit(X_train, y_train)
26
27# 4. Predict and Inspect Learned Rules
28predictions = model.predict(X_test)
29acc = accuracy_score(y_test, predictions)
30
31print(f"Max Depth: {max_depth}")
32print(f"Splitting Criterion: {criterion}")
33print(f"Test Accuracy: {acc:.2f}")
34print("\nLearned Decision Rules (ASCII Tree):")
35print(export_text(model, feature_names=list(X.columns)))
Click "Run Code" above to execute this script in the sandbox and inspect live outputs.

Expected Output

Accuracy: 1.0

|--- Age <= 36.50
| |--- class: 0
|--- Age >  36.50
| |--- class: 1

This is a deliberately simple teaching dataset, so the test split is easy. A perfect score here does not mean Decision Trees will achieve 100% accuracy on real-world data.


Common Questions About Decision Trees

Do Decision Trees need feature scaling?

Usually no. A tree compares feature values with thresholds, so ordinary rescaling does not change the ordering of values. Categorical data may still need suitable preprocessing depending on the implementation.

What does max_depth do?

It limits how many levels the tree can grow. A smaller depth can make the model easier to interpret and can help control overfitting.

Decision Tree or Random Forest?

A single tree is easier to inspect. A Random Forest combines many trees and often gives more stable predictions, at the cost of some simplicity.

Final Summary

Decision Trees are an intuitive supervised-learning model because their predictions can be followed as a sequence of feature-based questions and branches.

A single tree can model nonlinear relationships and usually does not need ordinary feature scaling, but an unconstrained tree can overfit. Decision Trees are also important building blocks for ensemble methods such as Random Forest and Gradient Boosting.

Most Important Insight to Remember:

A Decision Tree is easy to inspect, but controlling its depth and validating it on unseen data are important because a single tree can be sensitive to the training sample.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Decision Trees"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A tree repeatedly splits feature space into more homogeneous regions.
  • Classification splits reduce impurity; regression splits reduce target error.
  • Trees learn nonlinear interactions without requiring feature scaling.
  • Deep trees can memorize, so depth, leaf size, and pruning control variance.
  • Feature importance does not prove causality.
  • Small data changes can alter the tree, so validate stability.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
At a node with 60 class-A and 40 class-B examples, what is the Gini Impurity?
Question 2 of 4
What does setting min_samples_leaf=20 do, and how does it affect bias-variance?
Question 3 of 4
Decision trees are described as 'high variance' models. What does this mean concretely?
Question 4 of 4
A shallow tree (max_depth=3) consistently misclassifies the same 15% of examples regardless of training sample. What is the likely problem?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1At a node with 60 class-A and 40 class-B examples, what is the Gini Impurity?▼

Correct Answer: 1 - (0.6² + 0.4²) = 1 - (0.36 + 0.16) = 0.48

Gini = 1 - Σpᵢ² = 1 - (0.36+0.16) = 0.48. A perfectly pure node (all one class) has Gini=0. This 60/40 split is relatively impure — the tree looks for a feature split that reduces this in both child nodes.

2What does setting min_samples_leaf=20 do, and how does it affect bias-variance?▼

Correct Answer: Each leaf node must contain at least 20 training examples. This prevents the tree from creating leaves for individual examples — increasing bias slightly but substantially reducing variance by preventing memorisation of small groups

Without min_samples_leaf, a tree can create leaves for single examples (perfect training accuracy, terrible generalisation). min_samples_leaf forces the tree to generalise — each split must be supported by at least 20 examples.

3Decision trees are described as 'high variance' models. What does this mean concretely?▼

Correct Answer: Train a tree on 80% of your data, then on a slightly different 80% sample — the two trees will have different structures, different split features, different thresholds. Small changes in training data produce large changes in the model. This is high variance

This is the precise definition of variance in the bias-variance sense. Random Forest reduces this by averaging many such trees — each trained on different bootstrap samples with different feature subsets.

4A shallow tree (max_depth=3) consistently misclassifies the same 15% of examples regardless of training sample. What is the likely problem?▼

Correct Answer: High bias (underfitting) — the tree is too shallow to capture patterns for those 15% of examples. Consistent misclassification that doesn't depend on which training sample is used is the signature of systematic failure, not noise sensitivity

Systematic, consistent errors that don't depend on training sample are the signature of high bias. The model is missing something fundamental. Fix: increase max_depth, add features, or try a non-linear model.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next