Machine Learning from Scratch – Day 9: Understanding Random Forest
Understanding Random Forest
Series: Machine Learning From Scratch (18 articles)
- …
- 9Machine Learning from Scratch – Day 9: Understanding Random Forest This article
Introduction
Welcome to Day 9 of our Machine Learning from Scratch series!
In Day 8, we explored Decision Trees and learned how machines make predictions using a sequence of questions and conditions.
But here's an interesting question:
What if instead of relying on one Decision Tree, we use hundreds of Decision Trees together to make a prediction?
Would the predictions become more reliable?
This is the basic idea behind Random Forest, one of the most popular Machine Learning algorithms.
Let's understand how it works!
1. What is Random Forest?
Random Forest is a Supervised Machine Learning algorithm that combines multiple Decision Trees to make predictions.
Instead of depending on a single tree, it creates several trees and combines their outputs.
This approach is known as Ensemble Learning.
The basic idea is simple:
- A single Decision Tree makes a prediction.
- Multiple Decision Trees make independent predictions.
- Random Forest combines these predictions to produce a final result.
Real-world applications:
- Fraud detection.
- Disease prediction.
- Customer churn prediction.
- Credit risk assessment.
- Product recommendation analysis.
2. Why Do We Need Random Forest?
Let's consider a simple example.
Imagine a bank wants to predict whether a customer is eligible for a loan.
A single Decision Tree might make a prediction based on:
- Customer income.
- Credit score.
- Employment history.
- Existing loans.
However, a single tree can sometimes make incorrect predictions because of the specific training data it receives.
Now imagine using 100 different Decision Trees.
Each tree analyzes the data and produces its own prediction.
The Random Forest combines their results to make the final decision.
This generally improves stability and reduces the risk of overfitting compared with an individual, unrestricted Decision Tree.
3. How Does Random Forest Work?
Random Forest follows a process involving several important steps.
Step 1: Bootstrap Sampling
The algorithm creates multiple random training datasets by sampling from the original dataset with replacement.
This means some records may appear multiple times, while others may not appear in a particular sample.
Step 2: Building Multiple Decision Trees
Each sampled dataset is used to train a separate Decision Tree.
However, Random Forest introduces another layer of randomness.
At each split, a tree considers only a random subset of available features rather than all features.
Step 3: Making Predictions
Every Decision Tree makes its own prediction using the input data.
Step 4: Combining Predictions
The algorithm combines the predictions to produce the final result.
For classification, it commonly uses majority voting.
For regression, it generally uses the average of individual predictions.
4. Understanding Majority Voting
Let's understand majority voting with an example.
Suppose five Decision Trees predict whether an email is spam.
Decision Tree | Prediction |
|---|---|
Tree 1 | Spam |
Tree 2 | Not Spam |
Tree 3 | Spam |
Tree 4 | Spam |
Tree 5 | Not Spam |
The final votes are:
- Spam: 3 votes.
- Not Spam: 2 votes.
Final Prediction: Spam
Since Spam receives the majority of votes, Random Forest classifies the email as Spam.
This voting mechanism helps reduce the influence of individual tree errors, especially when the trees make sufficiently different errors.
5. Types of Random Forest
Random Forest supports two major types of prediction problems.
A. Random Forest Classifier
Used to predict categories.
Examples:
- Spam or Not Spam.
- Fraud or Genuine.
- Pass or Fail.
- Disease classification.
B. Random Forest Regressor
Used to predict continuous numerical values.
Examples:
- House price prediction.
- Sales forecasting.
- Demand estimation.
- Temperature prediction.
6. Important Concepts in Random Forest
Let's understand some technical terms that are important when working with Random Forest.
Concept | Meaning |
|---|---|
Ensemble Learning | Combining multiple models |
Bootstrap Sampling | Sampling data with replacement |
Bagging | Training models on different bootstrap samples |
Feature Randomness | Selecting random subsets of features |
Majority Voting | Selecting the most frequently predicted class |
Feature Importance | Estimating the contribution of features to tree predictions |
One interesting feature of Random Forest is that it can estimate feature importance.
For example, in house price prediction, it may identify area, location, and number of bedrooms as influential features.
However, feature importance should be interpreted carefully because correlated features can affect these estimates.
7. Practical Implementation Using Python
Now let's build a Random Forest classification model using Scikit-learn.
We'll use the Iris dataset to classify flowers into different species.
Step 1: Import the libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_scoreStep 2: Load the dataset
iris = load_iris()X = iris.datay = iris.targetStep 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)Step 4: Create and train the model
model = RandomForestClassifier( n_estimators=100, random_state=42)model.fit(X_train, y_train)Step 5: Make predictions
predictions = model.predict(X_test)print("Predictions:", predictions)Step 6: Evaluate the model
accuracy = accuracy_score(y_test, predictions)print("Model Accuracy:", accuracy)Step 7: Check feature importance
for feature, importance in zip( iris.feature_names, model.feature_importances_): print(feature, importance)What did we accomplish?
- Loaded a real-world dataset.
- Divided it into training and testing sets.
- Created 100 Decision Trees.
- Trained the Random Forest model.
- Predicted flower categories.
- Evaluated model accuracy.
- Examined feature importance.
We have successfully implemented Random Forest using Python!
8. Advantages and Limitations
Advantages | Limitations |
|---|---|
Generally more stable than a single tree | Requires more computational resources |
Handles classification and regression | Can be slower with many trees |
Captures complex relationships | Less interpretable than one Decision Tree |
Supports feature importance estimates | Can require memory for large forests |
An important point: More trees do not automatically guarantee better performance. Increasing the number of trees can improve stability, but it also increases computational cost.
Conclusion
Today, we explored Random Forest and learned how combining multiple Decision Trees can improve prediction reliability.
Let's revise the important concepts:
- Random Forest is a Supervised Learning algorithm.
- It belongs to Ensemble Learning.
- It uses Bootstrap Sampling to create different training datasets.
- It introduces randomness in feature selection.
- Classification uses majority voting.
- Regression generally uses averaging.
-
n_estimatorscontrols the number of trees.
The most important takeaway is that sometimes combining multiple models can produce more reliable predictions than depending on a single model.
Coming Next – Day 10: Understanding K-Nearest Neighbors (KNN).
We'll explore how machines classify data by looking at the nearest data points and identifying similarities between them.
Series: Machine Learning From Scratch (18 articles)
- …
- 9Machine Learning from Scratch – Day 9: Understanding Random Forest This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article