Machine Learning Lab / Supervised Learning / Random Forest
Algorithm 05 · Supervised learning · Classification and regression

Random Forest

Random Forest builds many Decision Trees and combines their answers. For classification, the trees vote. For regression, their numeric predictions are usually averaged. The group often gives a more reliable result than one tree alone.

Beginner friendly

What does it do?

It combines predictions from a collection of trees.

Many trees → Combine answers → Final predictionA forest is a team of decision trees

Imagine asking 25 different decision trees whether a student will pass. If 19 trees say Pass and 6 say Fail, the forest predicts Pass.

Quick facts

Input

Features such as study hours and attendance.

Output

A class or a number.

Learning style

Supervised: trees learn from labelled examples.

Main idea

Randomness makes trees different; combining them reduces the effect of one tree's mistakes.

1. How does Random Forest work?

Each tree gets a slightly different view of the training data.

A forest votes together

This diagram shows five sample trees. Each one gives a prediction. The forest uses the majority vote.

Tree 1Tree 2Tree 3Tree 4Tree 5PassPassFailPassPassMajority vote4 Pass · 1 FailFinal prediction: PASSEach tree contributes one vote

Four steps in training

Create random samples

Each tree trains on a bootstrap sample: rows are drawn at random, with replacement.

Grow a decision tree

At each split, the tree considers a random subset of features.

Repeat many times

Build many trees so they do not all make exactly the same decisions.

Combine their answers

Use majority vote for classification or an average for regression.

Remember: Random Forest is an ensemble method. Ensemble means combining several models to work as a team.

2. Live Random Forest Playground

Change the number of trees and see how their votes combine.

Interactive experiment

Tree voting board

Each tree casts one vote for Pass or Fail.

Pass voteFail vote

Experiment controls

Choose the number of trees and change how mixed the sample is.

Total trees—In this forest
Pass votes—Tree votes
Fail votes—Tree votes
Agreement—Share for winner
Build the forest to see its combined prediction.
This is a teaching simulation of different tree votes, not a full tree-training engine.

3. The mathematics behind Random Forest

The final answer is made by combining the predictions of the individual trees.

Classification: majority vote

ŷ = mode(T₁(x), T₂(x), …, Tₙ(x))Choose the class predicted by the most trees

Mode means the most common answer. If 7 out of 10 trees predict Pass, Pass wins.

Regression: average

ŷ = (T₁(x) + … + Tₙ(x)) / nAverage the numeric predictions

If trees predict 20, 22, and 24 lakh, the forest prediction is 22 lakh.

Bootstrap sampling

Sample rows with replacementA row can be selected more than once

Each tree receives a slightly different training sample. Some original rows are left out for that tree.

Random feature selection

Try a random subset of featuresAt each split in a tree

This makes trees less alike. Their combined predictions can be more stable than one large tree.

Out-of-bag (OOB) idea: Because each tree leaves out some training rows when it bootstraps, those left-out rows can help estimate performance without a separate validation split. OOB scoring is an estimate, not a replacement for a final test set.

4. Numerical worked example

Let's combine the predictions of seven trees.

Example: Will a student pass?

A forest has seven trees. Their predictions are: Pass, Pass, Fail, Pass, Pass, Fail, Pass.

Step 1: Count votes
Pass = 5 trees
Fail = 2 trees
Total = 7 trees
Step 2: Calculate vote share
Pass share = 5/7 ≈ 71.4%
Fail share = 2/7 ≈ 28.6%
Final prediction: Pass. Five trees voted Pass, so Pass wins the majority vote.

5. How do we evaluate Random Forest?

Use the same task-specific measures used for other classification or regression models.

For classification

Accuracy

Share of predictions that are correct.

Precision, recall and F1

Useful when classes are uneven or mistakes have different costs.

Confusion matrix

Shows which classes the forest mixes up.

For regression

MAE

Average size of prediction errors.

MSE / RMSE

Penalise larger prediction errors more strongly.

R²

Compares predictions with a simple average-based baseline.

Important: More trees can make predictions more stable, but they also need more memory and time. Always evaluate on data the model did not train on.

6. Python implementation

Train a Random Forest classifier with scikit-learn.

Example code

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

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import classification_report

# 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],
    [2, 45], [4, 68], [6, 72], [8, 88], [9, 96]
])
# 0 = Fail, 1 = Pass
y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
              0, 0, 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
)

model = RandomForestClassifier(
    n_estimators=100,
    max_depth=4,
    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))
print(classification_report(y_test, predictions))

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

# See which features were useful to the fitted forest
print("Feature importances:", model.feature_importances_)

7. Real-life applications

Random Forest is useful when many features may work together to predict an outcome.

Fraud detection

Flag transactions with patterns similar to known suspicious activity.

Customer churn

Estimate whether customers may stop using a service.

Student performance

Explore how attendance, study time and other factors relate to results.

Price prediction

Estimate numeric values such as house prices using many property features.

Strengths: often strong on tabular data, handles complex patterns, and is less sensitive to one tree's quirks. Limitations: less easy to explain than one small tree, can use more computing resources, and feature importance needs careful interpretation.

8. Knowledge check

Answer each question, then submit to see your score and explanations.

0 of 10 answered