edSlash Labs  /  Machine Learning Lab  /  Supervised Learning  /  Decision Trees
Algorithm 03 · Supervised learning · Classification and regression

Decision Trees

A Decision Tree learns a set of simple questions from examples. It follows the answers down branches until it reaches a prediction, much like a flowchart.

Beginner friendly

What does it do?

It splits data into smaller groups by asking questions.

Question → Branch → Question → PredictionA tree is a flowchart that learns its own questions from data

Imagine predicting whether a student passes. The tree may first ask, “Did the student study at least 5 hours?” It may then ask another question about attendance.

Quick facts

Input

Features such as study hours or attendance.

Output

A class (pass/fail) or a number (such as a house price).

Learning style

Supervised: it learns from examples with known answers.

Model shape

A tree made of decision questions and final leaves.

1. How does it work?

Follow the questions from the top of the tree to a final answer.

A tiny pass/fail decision tree

This is a simple teaching example. A real tree learns its question cut-offs from training data.

Study hours ≥ 5?Root question Attendance ≥ 75%?Another question Predict: PassLeaf Predict: PassLeaf Predict: FailLeaf NoYesYesNoA path through questions ends at a prediction
Root / questionPass leafFail leaf

Four important tree words

Root

The first question at the top of the tree.

Branch

The path taken after an answer, such as Yes or No.

Internal node

A question asked between the root and the final answer.

Leaf

The final prediction. It does not ask another question.

Remember: A Decision Tree is easy to follow because each path is a chain of simple questions.

2. Live Decision Tree Playground

Change the feature values and tree depth. Watch the learned questions and predictions change.

Interactive experiment

Learned decision tree

Study hours and attendance are used to predict pass or fail.

Decision questionPass leafFail leaf

Experiment controls

Generate example students, then test a new student.

Training accuracy—On sample data
Tree depth—Learned levels
Students0Training examples
Pass examples—Actual labels
Generate a dataset, then test a new student.
The playground uses a simple educational tree learner.

3. The mathematics behind Decision Trees

The tree searches for questions that make the groups more organised.

Gini impurity

Gini = 1 − Σ pᵢ²pᵢ is the share of examples in class i

Gini measures how mixed a group is. A group containing only one class has Gini 0. A more mixed group has a higher score.

Entropy

Entropy = −Σ pᵢ log₂(pᵢ)Another way to measure how mixed a group is

Entropy is low when a group is mostly one class and high when classes are mixed evenly.

Information gain

Gain = Parent impurity − Child impurityWeighted child impurity is used

A good question reduces impurity. The tree compares possible questions and chooses one with a strong reduction.

For regression trees

Choose splits that reduce squared errorLeaves predict a number, often the average

For a number such as house price, a leaf predicts a numeric value rather than a category.

Beginner tip: You do not need to memorise every formula first. Understand the main idea: the tree tries to split examples into groups that are less mixed or have more similar numeric values.

4. Numerical worked example

See how a simple question can make a group purer.

Example: Four students in one group

Before splitting, the group has 2 Pass and 2 Fail examples.

Step 1: Gini before split
Pass share = 2/4 = 0.5
Fail share = 2/4 = 0.5
Gini = 1 − (0.5² + 0.5²) = 0.5
Step 2: Ask “Study hours ≥ 5?”
Yes group: 2 Pass, 0 Fail → Gini = 0
No group: 0 Pass, 2 Fail → Gini = 0
Step 3: Compare
Weighted Gini after split = 0. The question separated the two classes perfectly in this tiny example, so it gives a large impurity reduction.

5. How do we evaluate a Decision Tree?

Check how well it predicts new examples, not only the examples it learned from.

For classification trees

Accuracy

Share of predictions that are correct.

Precision and recall

Useful when false alarms and missed cases have different costs.

Confusion matrix

Shows true and false predictions for each class.

For regression trees

MAE

Average size of the prediction errors.

MSE / RMSE

Error measures that penalise larger mistakes more.

R²

Compares the model with a simple average-based baseline.

Watch out for overfitting: A very deep tree can memorise training examples and perform poorly on new data. Limit its depth, require enough examples in leaves, and test it on held-out data.

6. Python implementation

Build a classification tree with scikit-learn.

Example code

Study hours and attendance are the features; pass/fail is the target.

import numpy as np
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

# Each row is one student: [study hours, attendance %]
X = np.array([
    [1, 40], [2, 50], [3, 60], [4, 65], [5, 70],
    [6, 75], [7, 80], [8, 85], [9, 90], [10, 95]
])
# 0 = Fail, 1 = Pass
y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])

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

# Limit depth to help reduce overfitting
model = DecisionTreeClassifier(
    criterion="gini", max_depth=3, random_state=42
)
model.fit(X_train, y_train)

predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
print("Confusion matrix:\\n", confusion_matrix(y_test, predictions))

# Predict for a student: 6 study hours, 80% attendance
new_student = np.array([[6, 80]])
print("Predicted class:", model.predict(new_student)[0])
print("Class probabilities:", model.predict_proba(new_student)[0])

# Optional: draw the learned tree
plot_tree(model, feature_names=["Study hours", "Attendance"],
          class_names=["Fail", "Pass"], filled=True)

7. Real-life applications

Decision Trees can be used for both categories and numbers.

Student performance

Use attendance, study time, and assignment completion to estimate pass/fail risk.

Customer decisions

Help group customers by their likely response to an offer.

Loan review support

Explore patterns linked to repayment outcomes. Real lending needs fairness checks and human oversight.

Price estimation

A regression tree can estimate a numeric value such as a house price.

Strengths: easy to explain, handles different feature types, and can model non-linear patterns. Limitations: a single tree can change a lot when the training data changes and can overfit if it grows too deep.

8. Knowledge check

Answer all 10 questions, then submit to see your score and explanations.

0 of 10 answered