1. Home
  2. AI & Machine Learning
  3. Decision Tree

Decision Tree

A flowchart of yes/no questions learned from data. Watch each split appear as a wall on the floor while the tree grows above it.

Interactive 3DBeginner12 min readAI/MLUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

Each dot is a fruit with two features — sweetness and size — and a colour for its type. A decision tree learns a flowchart of yes/no questions that sorts them. Press Build tree.

Pseudocode

  1. procedure build(node, depth):
  2. if node is pure or depth == max: make it a leaf (majority class)
  3. for each feature f and threshold t:
  4. score the split by weighted Gini impurity of the two sides
  5. pick the split with the lowest impurity (biggest gain)
  6. build(left side: f < t, depth + 1)
  7. build(right side: f ≥ t, depth + 1)
Read this model as text · 10 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. Each dot is a fruit with two features — sweetness and size — and a colour for its type. A decision tree learns a flowchart of yes/no questions that sorts them. Press Build tree.
  2. All 42 fruits start in one group. Gini impurity = 0.622 (0 = pure, higher = more mixed). The tree will ask yes/no questions to split them into pure groups.
  3. Try every feature and threshold. The best question is "sweetness < 3.9?": it splits 42 points into 15 and 27, lowering impurity from 0.622 to 0.28. A wall appears on the floor.
  4. This group is pure: all Apple. Make it a leaf.
  5. Try every feature and threshold. The best question is "size < 3.9?": it splits 27 points into 7 and 20, lowering impurity from 0.436 to 0.07. A wall appears on the floor.
  6. This group is pure: all Banana. Make it a leaf.
  7. Try every feature and threshold. The best question is "sweetness < 4.2?": it splits 20 points into 2 and 18, lowering impurity from 0.095 to 0.05. A wall appears on the floor.
  8. Maximum depth reached — make a leaf that predicts the majority: Apple (Gini 0.5).
  9. This group is pure: all Cherry. Make it a leaf.
  10. Done! The floor is divided into rectangles, one per leaf. To classify a new fruit, start at the top and answer the questions until you reach a leaf. Decision trees are easy to read — but can overfit if allowed to grow too deep.

Try this in the 3D model

  • Press Build tree and read the first question. Why do you think it was chosen?
  • Rotate to look straight down. Each coloured rectangle on the floor is one leaf.
  • Find a leaf that still contains a wrong-coloured point. That's the noise the tree couldn't separate.
  • Press New data and see how different the tree becomes.

What is a decision tree?

A decision tree classifies things by asking a sequence of yes/no questions — exactly like a flowchart or the game “20 questions”:

Is sweetness < 4.2?
├─ yes → Apple
└─ no  → Is size < 5.1?
         ├─ yes → Banana
         └─ no  → Cherry

The machine-learning part is that the tree learns the questions by itself from labelled examples.

In the 3D model, each dot on the floor is a fruit with two features (sweetness, size) and its true type (colour). Every question becomes a wall that cuts the floor, and the tree diagram grows above.

How a split is chosen — Gini impurity

For a group of examples, the Gini impurity is

Gini = 1 − Σ (pₖ)²

where pₖ is the fraction of class k in the group. A pure group (all one class) has Gini 0; a 50/50 mix of two classes has 0.5.

To grow a node, the algorithm tries every feature and every threshold between neighbouring values, splits the group in two, and computes the weighted Gini of the children. It picks the split with the lowest weighted impurity — the biggest information gain. Then it repeats on each side (recursion).

When to stop

A node becomes a leaf (predicting its majority class) when:

  • it is pure, or
  • the maximum depth is reached, or
  • it has too few examples, or
  • no split improves impurity enough.

Without such limits the tree keeps splitting until every leaf has one point — it memorises the training data, including its noise. That’s overfitting.

Code

from sklearn.tree import DecisionTreeClassifier, export_text

# [sweetness, size] → fruit
X = [[2, 3], [3, 7], [1, 5], [6, 2], [7, 3], [8, 4], [6, 8], [7, 9], [9, 7]]
y = ["apple", "apple", "apple", "banana", "banana", "banana", "cherry", "cherry", "cherry"]

tree = DecisionTreeClassifier(criterion="gini", max_depth=3).fit(X, y)
print(export_text(tree, feature_names=["sweetness", "size"]))
print(tree.predict([[7, 2]]))   # ['banana']

A tiny Gini calculator to check the numbers yourself:

from collections import Counter

def gini(labels):
    n = len(labels)
    return 1 - sum((c / n) ** 2 for c in Counter(labels).values())

print(gini(["apple"] * 5))                    # 0.0  (pure)
print(gini(["apple", "banana"] * 3))          # 0.5  (50/50 mix)

Strengths and weaknesses

✅ Strengths ❌ Weaknesses
Easy to understand and explain Overfits easily if too deep
No need to scale features Small changes in data can change the tree a lot
Handles numbers and categories Axis-aligned splits — diagonal boundaries need many steps
Fast predictions A single tree is usually less accurate than ensembles

Random forests and boosting

Combining many trees fixes most weaknesses:

  • Random forest: train hundreds of trees on random samples of the data and features; let them vote.
  • Gradient boosting (XGBoost, LightGBM): build trees one after another, each fixing the previous ones’ mistakes. These win many tabular-data competitions.

Where are decision trees used?

Loan approval, medical triage, customer churn prediction, fraud detection — anywhere decisions must be explainable.

Common mistakes

  • Letting the tree grow without limits (overfitting).
  • Trusting a single tree’s feature importances too much.
  • Forgetting that entropy / information gain is an alternative to Gini (results are usually similar).

Complexity at a glance

Case / operationTimeWhy
PredictionO(depth)Answer one question per level.
Training (n points, d features)O(d · n log n · depth)Sort values to try every threshold.
Extra spaceO(number of nodes)

Quick check

Test yourself — pick an answer to see if you got it.

1. What does Gini impurity measure?

2. How does the tree choose a split?

3. A very deep tree that is perfect on training data but bad on new data is…

4. Which ensemble method combines many decision trees?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Decision Tree. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.