DEV Community

Cover image for Random Forest Classifier
Rudra prasad Panigrahi
Rudra prasad Panigrahi

Posted on

Random Forest Classifier

Random Forest Classifier: How Can Multiple Decision Trees Work Together to Make Better Predictions?

Machine Learning Series | Classification Algorithms | Article 04/10

Imagine you have an important question in your examination:

"Which career should I choose?"

Would you trust the opinion of just one person?

Probably not!

You might ask your teachers, parents, friends and seniors. Everyone will give you their opinion based on their own experience.

After listening to everyone, you compare their suggestions and make a better decision.

Now, imagine teaching a computer to do something similar.

Instead of depending on just one Decision Tree, what if we create many Decision Trees and allow them to work together?

Each tree makes its own prediction. Then, all the trees combine their answers to produce a final prediction.

Interesting, right?

This is the basic idea behind Random Forest.

In our previous article, we learned how a Decision Tree makes predictions by asking a sequence of questions.

Today, we'll take that idea further and understand how multiple Decision Trees can work together.

We'll explore Random Forest from the basics, understand Ensemble Learning, Bagging, Bootstrap Sampling, Majority Voting, mathematical concepts, Python implementation and real-world applications.

Let's begin!


1. First, What Is Random Forest?

Before understanding Random Forest, let's remember something from our previous article.

A Decision Tree makes predictions by following a sequence of questions.

For example, imagine we want to predict whether an email is spam or not spam.

A Decision Tree might ask:

  • Does the email contain suspicious words?
  • Does it contain unknown links?
  • Is the sender unfamiliar?

Based on the answers, it predicts whether the email is Spam or Not Spam.

But what if this single tree makes a wrong prediction?

Can we improve the result?

Yes!

Instead of depending on one tree, Random Forest creates multiple Decision Trees.

Each tree learns from a slightly different sample of the training data and considers a randomly selected subset of features when searching for splits.

After learning, all the trees make predictions.

The Random Forest combines their predictions to produce the final answer.

Random Forest is a supervised Machine Learning algorithm that combines multiple Decision Trees to make predictions.

It can be used for:

  • Classification: Predicting categories.
  • Regression: Predicting numerical values.

The word "Forest" represents a collection of trees.

And the word "Random" comes from the randomness introduced during training.

That's why we call it Random Forest!

2. Why Do We Need Random Forest After Decision Trees?

Let's understand this with an example.

Imagine you ask one student to answer 20 difficult questions.

The student might answer some correctly and make mistakes on others.

Now imagine asking 20 students the same questions.

Each student has different strengths and weaknesses.

If you combine their answers using majority voting, the final answer may be more reliable than depending on just one student.

Random Forest follows a similar idea.

A single Decision Tree can become too sensitive to the training data.

For example:

  • It may learn unnecessary patterns.
  • It may memorize training examples.
  • Small changes in the dataset can produce a very different tree.
  • It may perform poorly on new data.

This problem is called Overfitting.

Random Forest reduces the risk of overfitting by combining predictions from multiple trees trained with randomness.

However, remember that Random Forest does not guarantee better results in every situation. Its performance depends on the dataset and model settings.

3. What Is Ensemble Learning?

Before going deeper into Random Forest, we need to understand one important Machine Learning concept.

It's called Ensemble Learning.

Imagine you want to know whether a particular movie is worth watching.

You ask five friends:

  • Friend 1: Yes.
  • Friend 2: Yes.
  • Friend 3: No.
  • Friend 4: Yes.
  • Friend 5: No.

Three friends say Yes, while two say No.

The majority says Yes.

You might decide to watch the movie based on their combined opinions.

Ensemble Learning works in a similar way.

Ensemble Learning is a Machine Learning technique that combines multiple models to produce a final prediction.

Instead of depending on one model, it uses several models working together.

There are three popular Ensemble Learning techniques:

A. Bagging (Bootstrap Aggregating)

Multiple models are trained independently using different random samples of the training dataset.

Their predictions are then combined.

Random Forest uses this technique.

B. Boosting

Models are trained sequentially, with later models focusing on correcting errors made by earlier models.

Examples:

  • AdaBoost.
  • Gradient Boosting.
  • XGBoost.

C. Stacking

Different types of Machine Learning models are combined using another model called a Meta-Model.

The Meta-Model learns how to combine their predictions.

Remember:

Random Forest primarily uses Bagging.

4. What Is Bagging?

Bagging stands for Bootstrap Aggregating.

Let's understand the name first.

  • Bootstrap means creating random samples from the original dataset with replacement.
  • Aggregating means combining the predictions from multiple models.

Imagine you have a classroom containing 100 students.

You want to create five different groups for a learning activity.

Instead of dividing the students into five fixed groups, you randomly select students for each group.

A student may appear in more than one group.

Some students may not appear in a particular group at all.

This is similar to what happens in Bagging.

Each Decision Tree receives its own bootstrap sample.

The trees are trained independently.

After training, their predictions are combined.

Why is Bagging useful?

A single Decision Tree can be unstable.

Bagging helps reduce prediction variance by combining several models trained on different bootstrap samples.

It makes the overall model less dependent on the particular training sample used by one tree.

5. What Is Bootstrap Sampling?

This is one of the most important concepts in Random Forest.

Imagine our original dataset contains five records:

Student Study Hours Result
A 2 Fail
B 5 Pass
C 3 Fail
D 7 Pass
E 8 Pass

Now, Random Forest creates a random sample from this dataset.

For example:

Original Dataset: A, B, C, D, E

Bootstrap Sample 1:

A, B, B, D, E

Bootstrap Sample 2:

C, C, D, E, A

Bootstrap Sample 3:

B, D, D, E, A

Notice something?

Some records appear more than once, while some are missing.

This happens because sampling is performed with replacement.

That means after selecting one record, it can be selected again.

Each tree gets a different bootstrap sample and learns from it.

What is Out-of-Bag Data?

Suppose Bootstrap Sample 1 contains:

A, B, B, D, E

Student C was not selected.

That record is called an Out-of-Bag (OOB) observation for that particular tree.

Random Forest can use these observations to estimate model performance without requiring a separate validation dataset.

Each tree has its own OOB observations.

By combining predictions for observations that were left out of the corresponding bootstrap samples, we can calculate an OOB score.

This is useful for model evaluation.

6. What Is Random Feature Selection?

Now comes another important concept.

We already know that each tree receives a different random sample of training records.

But Random Forest introduces another type of randomness.

It also selects a random subset of features when searching for the best split at each node.

Let's understand this with an example.

Imagine we want to predict whether a customer will purchase a product.

Our dataset contains:

  • Age.
  • Salary.
  • Shopping Frequency.
  • Website Visits.
  • Previous Purchases.
  • Location.

A normal Decision Tree may examine all available features when searching for the best split.

But in Random Forest, each split considers only a randomly selected subset of features.

For example:

Tree 1 considers:

  • Age.
  • Salary.
  • Website Visits.

Tree 2 considers:

  • Shopping Frequency.
  • Previous Purchases.
  • Location.

Tree 3 considers:

  • Age.
  • Previous Purchases.
  • Salary.

The actual subsets are selected randomly during training.

This encourages different trees to learn different patterns.

Why do we need random feature selection?

Imagine all Decision Trees always use the same strongest feature.

Their structures may become very similar.

If they all make similar mistakes, combining their predictions will not help much.

Random feature selection encourages diversity between trees.

Important: In Scikit-learn, max_features controls how many features are considered when searching for the best split at each node.

7. How Does Random Forest Actually Work?

Now let's connect everything.

Imagine we want to predict whether a customer will purchase a product.

Our training dataset contains thousands of customer records.

Random Forest follows these steps:

Step 1: Start with the original dataset

The algorithm receives the training data.

Step 2: Create bootstrap samples

It generates different random samples from the original dataset.

Step 3: Build multiple Decision Trees

Each tree learns from its own bootstrap sample.

Step 4: Randomly select features

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

Step 5: Train all trees

Each Decision Tree independently learns its decision rules.

Step 6: Make predictions

When a new customer enters the model, every tree makes its own prediction.

Step 7: Combine the predictions

For classification, the trees vote for the predicted class.

The class receiving the most votes becomes the final prediction.

For regression, predictions are generally averaged.

That's how Random Forest works!

8. What Is Majority Voting?

Imagine we have five Decision Trees.

We want to predict whether a transaction is fraudulent.

Each tree gives its prediction:

Decision Tree Prediction
Tree 1 Fraud
Tree 2 Genuine
Tree 3 Fraud
Tree 4 Fraud
Tree 5 Genuine

Let's count the votes.

  • Fraud = 3 votes.
  • Genuine = 2 votes.

Therefore:

Final Prediction = Fraud

This process is called Majority Voting.

The model combines the predictions from all trees and selects the class receiving the most votes.

What if there is a tie?

In a classification problem, class probabilities and the implementation's tie-breaking rules determine the final prediction.

In Scikit-learn, RandomForestClassifier combines the class probabilities predicted by individual trees and selects the class with the highest mean probability.

9. Mathematical Understanding of Random Forest

Let's understand the mathematics without making it unnecessarily complicated.

A. Classification

Suppose we have a Random Forest containing N Decision Trees.

Each tree predicts a class.

The final prediction is the class that receives the highest number of votes.

We can represent this as:

ŷ = Mode(T₁(x), T₂(x), ..., Tₙ(x))

Where:

  • ŷ = Final predicted class.
  • T₁(x) = Prediction from Tree 1.
  • T₂(x) = Prediction from Tree 2.
  • Tₙ(x) = Prediction from Tree N.
  • N = Total number of trees.
  • Mode = Most frequently predicted class.

B. Regression

For regression, the model combines numerical predictions using an average.

Formula:

ŷ = (1/N) Σ Tᵢ(x)

Where:

  • ŷ = Final predicted numerical value.
  • N = Number of Decision Trees.
  • Tᵢ(x) = Prediction from the ith tree.

Simple example

Suppose five trees predict a house price:

  • Tree 1 = ₹30 lakh.
  • Tree 2 = ₹32 lakh.
  • Tree 3 = ₹28 lakh.
  • Tree 4 = ₹35 lakh.
  • Tree 5 = ₹30 lakh.

Final prediction:

= (30 + 32 + 28 + 35 + 30) / 5

= 155 / 5

Final Prediction = ₹31 lakh

This is how Random Forest combines predictions in regression.

10. Important Hyperparameters in Random Forest

Hyperparameters are settings that we choose before training the model.

Let's understand the most important ones.

Parameter Simple explanation
n_estimators Number of Decision Trees in the forest
criterion Measures used to evaluate splits
max_depth Maximum depth allowed for each tree
min_samples_split Minimum records needed to split a node
min_samples_leaf Minimum records required in a leaf
max_features Number of features considered at each split
bootstrap Whether bootstrap samples are used
random_state Controls reproducibility
oob_score Enables Out-of-Bag evaluation when bootstrap is enabled

Example

RandomForestClassifier(
    n_estimators=100,
    max_depth=5,
    random_state=42
)
Enter fullscreen mode Exit fullscreen mode

This creates a Random Forest containing 100 trees, with each tree limited to a maximum depth of 5.

11. Practical Implementation Using Python

Now let's build our own Random Forest Classifier.

We'll use the Iris dataset, just as we did in our previous Decision Tree article.

This will also help us compare the two algorithms.

Our problem

We want to predict the species of a flower using four measurements:

  1. Sepal Length.
  2. Sepal Width.
  3. Petal Length.
  4. Petal Width.

The possible output classes are:

  • Setosa.
  • Versicolor.
  • Virginica.

Let's implement it step by step.

Step 1: Import the required libraries

import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import (
    accuracy_score,
    classification_report,
    confusion_matrix
)
Enter fullscreen mode Exit fullscreen mode

What are these libraries for?

  • Matplotlib: Creates visualizations.
  • load_iris: Loads the Iris dataset.
  • train_test_split: Divides data into training and testing sets.
  • RandomForestClassifier: Creates our Random Forest model.
  • accuracy_score: Calculates prediction accuracy.
  • classification_report: Shows precision, recall and F1-score.
  • confusion_matrix: Shows correct and incorrect predictions.

Step 2: Load the dataset

iris = load_iris()

X = iris.data
y = iris.target

print("Features:", iris.feature_names)
print("Classes:", iris.target_names)

print("Dataset Shape:", X.shape)
Enter fullscreen mode Exit fullscreen mode

Here:

  • X contains the flower measurements.
  • y contains the flower species.

The dataset contains 150 observations and four input features.

Step 3: Split the dataset

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)
Enter fullscreen mode Exit fullscreen mode

Why do we split the data?

We use training data to teach our model and testing data to evaluate its performance on unseen observations.

Here:

  • 80% of the data is used for training.
  • 20% is used for testing.

The stratify parameter maintains the class proportions in both sets.

Step 4: Create the Random Forest model

model = RandomForestClassifier(
    n_estimators=100,
    criterion="gini",
    max_depth=5,
    random_state=42
)
Enter fullscreen mode Exit fullscreen mode

Let's understand the parameters:

  • n_estimators=100: Creates 100 Decision Trees.
  • criterion="gini": Uses Gini Impurity to evaluate splits.
  • max_depth=5: Limits the depth of each tree.
  • random_state=42: Helps reproduce the same randomized training process.

Step 5: Train the model

model.fit(X_train, y_train)

print("Random Forest Model Trained Successfully!")
Enter fullscreen mode Exit fullscreen mode

The fit() method trains all the trees using their respective bootstrap samples and randomized feature selection.

Step 6: Make predictions

y_pred = model.predict(X_test)

print("Predictions:", y_pred)
Enter fullscreen mode Exit fullscreen mode

The model now combines the predictions from its Decision Trees to predict the flower species.

Step 7: Evaluate the model

accuracy = accuracy_score(y_test, y_pred)

print("Accuracy:", accuracy)

print(
    classification_report(
        y_test,
        y_pred,
        target_names=iris.target_names
    )
)

print(confusion_matrix(y_test, y_pred))
Enter fullscreen mode Exit fullscreen mode

Let's understand the evaluation metrics:

Accuracy: How many predictions were correct out of all predictions?

Precision: When the model predicts a particular class, how often is it correct?

Recall: How many actual examples of a particular class did the model identify?

F1-score: A combined measure of precision and recall.

We should not judge a model using accuracy alone, especially when the classes are imbalanced.

Step 8: Visualize the results

A Random Forest contains multiple trees, so visualizing the entire forest at once can become difficult.

Instead, we can visualize one individual tree.

from sklearn.tree import plot_tree

plt.figure(figsize=(18, 10))

plot_tree(
    model.estimators_[0],
    feature_names=iris.feature_names,
    class_names=iris.target_names,
    filled=True,
    rounded=True,
    fontsize=9
)

plt.title("One Decision Tree from Random Forest")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Here:

  • estimators_ contains the trained Decision Trees.
  • estimators_[0] selects the first tree.
  • plot_tree() displays its decision structure.

Remember, this is only one tree from our entire forest!

Step 9: Check feature importance

An interesting feature of Random Forest is that we can examine which features were useful for making predictions.

import pandas as pd

importance = pd.DataFrame({
    "Feature": iris.feature_names,
    "Importance": model.feature_importances_
})

importance = importance.sort_values(
    by="Importance",
    ascending=False
)

print(importance)

importance.plot(
    x="Feature",
    y="Importance",
    kind="bar",
    legend=False
)

plt.title("Random Forest Feature Importance")
plt.ylabel("Importance")
plt.show()
Enter fullscreen mode Exit fullscreen mode

This helps us understand which features contributed most to the model's impurity-based splitting decisions.

Important: Feature importance does not prove that a feature causes the prediction. Correlated features can also affect how importance is distributed.

12. Random Forest vs Decision Tree

Since our previous article covered Decision Trees, let's compare both algorithms.

Feature Decision Tree Random Forest
Number of models One tree Multiple trees
Learning approach Single-tree learning Ensemble learning
Training Usually faster Usually more computationally expensive
Prediction Uses one tree Combines multiple trees
Overfitting Can overfit easily Often reduces variance
Interpretability Easier to understand More difficult to interpret
Feature scaling Usually unnecessary Usually unnecessary
Performance Depends on the tree Often stronger, but not guaranteed

The main difference:

A Decision Tree makes a prediction using one tree.

Random Forest combines predictions from multiple trees.

13. Advantages of Random Forest

Why is Random Forest so popular?

  1. Reduces overfitting risk: Combining multiple trees often reduces the variance of a single tree.
  2. Handles complex patterns: It can learn nonlinear relationships.
  3. Works for classification and regression: It supports both types of prediction.
  4. Feature importance: Helps identify useful features.
  5. Less preprocessing: Numerical features generally don't require normalization.
  6. Robust performance: It often provides strong results across different datasets.
  7. Out-of-Bag evaluation: Can estimate generalization performance using observations left out of bootstrap samples.

14. Disadvantages of Random Forest

Every algorithm has limitations.

  1. Higher computational cost: Training many trees requires more resources than training one tree.
  2. More memory usage: The model stores multiple Decision Trees.
  3. Less interpretable: Understanding the complete forest is harder than understanding one small tree.
  4. Prediction time: Making predictions may take longer because multiple trees must be evaluated.
  5. Not always the best choice: Some datasets may work better with simpler models or other algorithms.
  6. Feature importance limitations: Impurity-based feature importance can be biased toward certain types of features.

15. Real-World Applications of Random Forest

Let's see where Random Forest can be useful in real life.

1. Banking and Finance

Banks can use classification models to support credit risk assessment and identify potentially fraudulent transactions.

2. Healthcare

It can help classify medical records and identify patterns associated with certain conditions.

3. E-commerce

Online stores can predict customer purchasing behavior and identify customers who may stop using a service.

4. Cybersecurity

Random Forest can classify network traffic and help identify suspicious activities.

5. Agriculture

It can help classify crop conditions and support crop disease detection using relevant agricultural data.

6. Insurance

It can help classify insurance claims and identify patterns associated with potential claim risks.

These are potential applications, and real-world deployment requires suitable data, validation and domain expertise.

16. When Should We Use Random Forest?

Random Forest can be a good choice when:

  • You have a structured dataset.
  • You want a strong baseline classification model.
  • Your data contains nonlinear relationships.
  • You want to reduce the instability of a single Decision Tree.
  • You want to examine feature importance.
  • You don't need a very small, easily interpretable model.

However, if you need a highly interpretable model, a small Decision Tree or another explainable approach may be more appropriate.

17. What Have We Learned?

Let's quickly revise today's concepts.

  • Random Forest is an ensemble learning algorithm.
  • It combines multiple Decision Trees.
  • Bagging stands for Bootstrap Aggregating.
  • Bootstrap Sampling selects records with replacement.
  • Out-of-Bag data can help evaluate the model.
  • Random Feature Selection creates diversity between trees.
  • Majority Voting combines classification predictions.
  • Regression predictions are generally averaged.
  • Random Forest supports both classification and regression.
  • Hyperparameters help control model complexity.
  • Python's Scikit-learn makes implementation straightforward.

The biggest lesson from today's article:

One Decision Tree makes a decision using its own learned rules.

Random Forest brings multiple trees together, allows them to learn different patterns and combines their predictions.

Sometimes, learning from a group of models can be more reliable than depending on just one.

What's Next?

We've now completed four algorithms in our Machine Learning Classification Series:

  1. Logistic Regression.
  2. K-Nearest Neighbors (KNN).
  3. Decision Tree Classifier.
  4. Random Forest Classifier.

And our next topic is:

Article 05: Support Vector Machine (SVM) — How Does a Machine Find the Best Boundary Between Different Classes?

We'll understand:

  • What is a Support Vector Machine?
  • What is a decision boundary?
  • What is a hyperplane?
  • What is a margin?
  • What are support vectors?
  • What is the kernel trick?
  • Linear vs Nonlinear SVM.
  • Practical Python implementation.

If you're learning Machine Learning with me, let's continue this journey together.

My goal with this series is simple:

I don't just want to learn an algorithm. I want to understand it well enough to explain it to someone who is learning it for the very first time.

Learn it. Understand it. Build it. Teach it.

Happy Learning! 🚀

MachineLearning #RandomForest #Python #DataScience #Classification #EnsembleLearning #ScikitLearn

Top comments (0)