Skip to main content
LearnMLAcademy
Intermediate10 min read

Random Forest

Train Random Forest ensembles with bootstrap aggregation and tree bagging, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Random Forest

Random Forest is an ensemble learning algorithm that combines many Decision Trees for classification or regression.

Random Forest in Simple Words

A single Decision Tree gives one opinion. A Random Forest builds many slightly different trees and combines their predictions. The goal is not to make every tree identical or perfect; the goal is to make the group prediction more stable.

Tree 1

YES

Tree 2

YES

Tree 3

NO

→

Combined Result

YES

1. Make different trees

Use random training samples and random feature choices.

2. Ask every tree

Each tree predicts for the new example.

3. Combine answers

Aggregate the tree predictions into one final prediction.

Random Forest is popular because averaging many randomized trees often reduces the instability of a single deep Decision Tree while keeping the ability to learn nonlinear patterns and feature interactions. It is useful, but it is not automatically the best model for every dataset.

Random Forest belongs to Ensemble Learning: methods that combine multiple models to produce one prediction.

"Instead of depending on one Decision Tree, Random Forest combines predictions from many randomized Decision Trees."

The word Random refers mainly to randomness in the training samples and the features considered while growing the trees.


Why Random Forest Was Created

To understand Random Forest, first remember a limitation of Decision Trees: a deep tree can have high variance and may overfit the training data.

A single Decision Tree can be sensitive to the exact training sample. Small data changes can sometimes produce noticeably different splits and predictions. If the tree grows too complex, it can fit noise and specific training patterns that do not generalize well.

Instead of relying on one unstable tree, Random Forest creates many trees. Each tree learns slightly different patterns from the dataset. When all these trees combine together:

  • Some tree-specific errors can average out
  • Prediction variance can decrease
  • The model can become less sensitive to one particular training sample
  • Generalization may improve when the trees are sufficiently diverse

Simple Real-Life Analogy

Imagine a hospital where doctors are trying to diagnose a patient. Suppose only one doctor gives the diagnosis. There is always a possibility that the doctor may miss certain symptoms or misinterpret reports.

Now imagine a panel where several doctors review slightly different evidence and then combine their opinions. One opinion can be wrong, but a diverse group can sometimes be more stable than relying on one person alone. Random Forest uses a similar ensemble idea: many trees see randomized views of the training problem and their predictions are aggregated.

Core Idea Behind Random Forest

The central idea can be summarized as: Diverse trees + aggregation can produce a more stable predictor.

Individual trees can make different errors. Random Forest deliberately creates diversity through sample and feature randomness, then averages or combines the trees so that some uncorrelated errors can cancel out. This often reduces variance, although it does not guarantee higher accuracy on every dataset.

Understanding Decision Trees First

Random Forest is built using Decision Trees. A Decision Tree works like a flowchart where data gets repeatedly split based on conditions (e.g., Is Age > 30? → Is Income > 50K?). While highly interpretable, single Decision Trees often suffer from major weaknesses:

  • Overfitting risk: A deep tree can fit noise and very specific training patterns.
  • High variance: Small dataset changes can lead to different splits and predictions.
  • Noise sensitivity: Unrestricted trees may create branches around noisy observations.

Ensemble Learning Categories

Random Forest belongs to the broader field of Ensemble Learning. Three common ensemble strategies are:

  • Bagging (Random Forest relies heavily on this)
  • Boosting (e.g., XGBoost, AdaBoost, Gradient Boosting)
  • Stacking

High-Level Workflow

Training & Prediction Pipeline

  1. Create randomized training views: With bootstrap sampling enabled, each tree receives a sample drawn with replacement from the training data.
  2. Grow multiple Decision Trees: At each split, only a random subset of features is considered.
  3. Make predictions: Send the new example through every tree.
  4. Aggregate predictions: Combine the tree outputs rather than trusting one tree.
  5. Return the final prediction: Classification combines class evidence; regression averages numerical predictions.

Why the Word "Random" Is Important

Random Forest commonly introduces randomness in two ways: 1. Bootstrap sampling of training rows and 2. Random subsets of features at tree splits.

These mechanisms encourage the trees to be different. Lower correlation between tree errors is important because averaging nearly identical trees gives less variance reduction than averaging diverse trees.

Understanding Bagging

Random Forest uses an ensemble method called Bagging (Bootstrap Aggregating).

Bootstrap Sampling

Bootstrap sampling means random sampling with replacement. Suppose the original dataset contains [A, B, C, D, E]. One bootstrap sample could be [A, B, B, D, E]. Here, B appears twice and C is absent. Different bootstrap samples help create different trees.

Feature Randomness

Another powerful idea in Random Forest is Random Feature Selection. At each split in the tree, only a random subset of features is considered, NOT all features.

Example of Feature Randomness:

Suppose the dataset contains: [Age, Salary, Education, Experience, City]

  • At one split, Random Forest may consider only: [Salary, Experience]
  • At another split, it may consider: [Age, City]

Why does this help? If the same very strong feature dominated every split in every tree, the trees could become highly correlated. Considering random feature subsets encourages diversity between trees.

Tiny max_features Example

For classification, Scikit-learn's default is max_features="sqrt".

If a dataset has 16 features, then:

√16 = 4

So roughly 4 candidate features are considered when searching for a split at a node, rather than automatically considering all 16.

How Random Forest Makes Final Predictions

The prediction mechanism depends slightly on the problem type:

  • Classification intuition: Think of the trees as combining class votes or class evidence. If 4 trees favor "Yes" and 1 favors "No", the ensemble will typically favor "Yes".
  • Regression: Average the tree predictions. If five trees predict 100, 120, 110, 130, and 140, then:
    (100 + 120 + 110 + 130 + 140) ÷ 5 = 600 ÷ 5 = 120

Scikit-learn detail: RandomForestClassifier combines trees by averaging their class-probability predictions and then selects the class with the highest mean probability. So "majority voting" is a useful beginner intuition, but probability averaging is the more precise description for Scikit-learn.

Tiny binary example

Tree probabilities for YES: 0.90, 0.70, 0.40

Mean = (0.90 + 0.70 + 0.40) ÷ 3 = 2.00 ÷ 3 ≈ 0.667

The forest combines this probability evidence across trees rather than trusting one tree alone.

Mathematical Intuition (Bias-Variance)

Deep Decision Trees often have relatively low bias and high variance. Random Forest combines many randomized trees to reduce variance. This can come with a small increase in bias, but the variance reduction is often valuable. The exact trade-off depends on the data and hyperparameters.


Visualizing Random Forest Concepts

Classification: Combine Tree Opinions

Simple voting intuition with five trees.

Tree 1

Yes

Tree 2

Yes

Tree 3

No

Tree 4

Yes

Tree 5

No

3 Yes vs 2 No → beginner voting intuition: YES

Illustrative Feature Importance

Example values only — not a universal ranking.

Salary45%
Credit Score35%
Age10%
City10%

Scikit-learn's feature_importances_ is impurity-based. Treat it as a model interpretation aid, not proof that a feature is causally important.

Visual Explanation: How Bagging Creates Diversity

Bootstrapping takes random samples with replacement. This means some data points are picked multiple times, and some are left out (Out-of-Bag).

Original Dataset

Data A
Data B
Data C
Data D
Data E

Tree 1 (Sample)

Data A
Data B
Data B
Data D
Data E

Data B is repeated
Data C is left out

Tree 2 (Sample)

Data A
Data C
Data C
Data C
Data E

Data C is repeated
Data B, D are left out

Tree 3 (Sample)

Data B
Data D
Data E
Data E
Data A

Data E is repeated
Data C is left out

Out-of-Bag (OOB) Samples

During bootstrap sampling, some training rows are not selected for a particular tree. These are Out-of-Bag (OOB) samples for that tree. When oob_score=True and bootstrapping is enabled, Scikit-learn can use these held-out observations to produce an OOB performance estimate. This is useful for an additional estimate of generalization, but it should not be treated as a reason to repeatedly tune against the final test set or to skip a final independent evaluation when one is needed.

Important Hyperparameters

To properly tune a Random Forest, you need to understand these key components:

  • n_estimatorsControls the number of trees. More trees can make the ensemble estimate more stable, but improvements eventually show diminishing returns while training and prediction cost continue to grow.
  • max_depthControls the maximum depth of each tree. Small depth creates simpler trees. Large depth creates more complex trees and may increase overfitting risk.
  • max_featuresControls how many candidate features are considered at each split. Smaller values increase randomness, but making the subset too small can also weaken individual trees.
  • min_samples_splitMinimum number of samples required to execute a split at an internal node.
  • min_samples_leafMinimum number of samples required to be at a leaf node (the end points of the tree).
  • oob_scoreWhen bootstrapping is enabled, setting this to True asks Scikit-learn to compute an out-of-bag score from training observations left out of individual bootstrap samples.

Do Random Forests Need Feature Scaling?

Usually, ordinary standardization is not required for Random Forests because tree splits compare values against thresholds rather than using Euclidean distance. Scaling can still be part of a broader preprocessing pipeline, but it is not needed for the same reason it is important for KNN or SVM.

Feature Importance Warning

Impurity-based importance can favor features with many possible split points and is computed from the fitted trees. Use it carefully, and consider permutation importance on held-out data when you want to know whether a feature truly helps predictive performance.


Why Random Forest Performs So Well

Random Forest is often a strong baseline on tabular supervised-learning problems because it combines nonlinear Decision Trees with variance-reducing aggregation and randomization.

Its performance depends on the signal in the features, the amount of data, tree diversity, class balance, evaluation metric, and hyperparameters. It should still be compared with appropriate baseline and alternative models.

Advantages vs Disadvantages

Advantages

  • Strong baseline: Often performs well on many tabular classification and regression problems.
  • Variance reduction: Averaging diverse trees can reduce the instability of a single tree.
  • Nonlinear patterns: Captures thresholds, interactions, and nonlinear relationships without manually specifying them.
  • Feature insights: Provides impurity-based feature_importances_, with interpretation caveats.
  • Little scaling dependence: Standard feature scaling is usually unnecessary for ordinary tree splits.

Disadvantages

  • Computationally Heavy: Training hundreds of trees requires significant memory and CPU power.
  • Prediction cost: Each prediction must be evaluated across many trees, which can matter in low-latency systems.
  • Less interpretable: A forest is harder to inspect directly than a single small Decision Tree, so additional interpretation tools may be needed.
  • Sparse Data: Can underperform on highly sparse data (like heavy NLP TF-IDF matrices).
Healthcare
  • Clinical risk prediction
  • Research classification
Finance & Banking
  • Credit Scoring
  • Fraud Detection
  • Default-risk modeling
E-Commerce
  • Purchase propensity
  • Customer churn prediction
  • Return / fraud classification

Python Implementation

Here is a complete, practical pipeline utilizing Scikit-Learn to train a Random Forest ensemble on the Iris classification dataset.

Python Code: Random Forest Classifier

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

# Step 1: Load dataset
data = load_iris()
X = data.data
y = data.target

# Step 2: Create an untouched test set
X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

# Step 3: Train 100 randomized trees
model = RandomForestClassifier(
    n_estimators=100,
    random_state=42,
    oob_score=True
)
model.fit(X_train, y_train)

# Step 4: Predict unseen test examples
predictions = model.predict(X_test)

# Step 5: Evaluate
accuracy = accuracy_score(y_test, predictions)
print(f"Test accuracy: {accuracy:.2f}")
print(f"OOB score: {model.oob_score_:.2f}")

# Step 6: Inspect impurity-based feature importance
print("Feature importances:", model.feature_importances_.round(3))
Terminal Output

$ python random_forest_iris.py

Test accuracy: 0.90

OOB score: 0.94

Feature importances: [0.116 0.015 0.431 0.437]

What the output means

  • Test accuracy = 0.90: 90% of this small test split was classified correctly.
  • OOB score = 0.94: the forest's out-of-bag estimate on the training set is about 94% for this run.
  • Feature importances: the last two Iris measurements receive most of the impurity-based importance in this fitted forest.

This is a small educational dataset. A good score here does not imply the same performance on a real-world problem, and exact floating-point output can vary slightly across library versions.


Complete Random Forest Pipeline

Here is the high-level flow of data from start to finish within a Random Forest algorithm:

Collect Dataset
▼
Bootstrap Sampling
▼
Create Multiple Trees
▼
Random Feature Selection
▼
Grow Trees with Randomized Splits
▼
Combine Predictions
▼
Generate Final Output

Common Mistakes

Assuming more trees always fix the model

More trees can stabilize the ensemble, but they cannot create signal that is missing from the features.

Treating feature importance as causal proof

A high importance score says the fitted forest used a feature strongly; it does not prove that changing the feature causes the target to change.

Tuning on the test set

Use training/validation procedures for model selection and keep the final test set for final evaluation.

Believing Random Forest cannot overfit

A forest often overfits less than one deep tree, but overfitting is still possible, especially with leakage or inappropriate tuning.

Quick FAQs

Is Random Forest just many identical Decision Trees?

No. Randomness in training rows and candidate features is used to encourage tree diversity.

Does Random Forest need feature scaling?

Usually not for ordinary threshold-based tree splits.

What should I learn next?

Continue with Bagging, then compare it with Boosting. You can also revisit Decision Trees and Bias-Variance.

Final Summary

Random Forest is a widely used supervised-learning algorithm that combines many randomized Decision Trees. Instead of relying on one high-variance tree, it aggregates a forest of diverse trees.

Its key idea is: diverse models can become more stable when their predictions are aggregated.

Depending on the data and settings, this design can improve:

  • Accuracy
  • Stability
  • Generalization
  • Robustness

Most Important Insight to Remember:

"The central idea behind Random Forest is: create diverse trees, then aggregate their predictions. The benefit comes mainly from reducing the variance and correlation problems that can affect a single Decision Tree."

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Random Forest"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A random forest averages trees trained on bootstrap samples.
  • Random feature subsets reduce correlation between trees.
  • Averaging usually lowers variance compared with one deep tree.
  • Out-of-bag examples can estimate performance.
  • Feature importance can be biased and must be interpreted carefully.
  • Tune capacity and tree count against quality and resource cost.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
Why does a Random Forest typically outperform a single Decision Tree?
Question 2 of 4
What is the Out-of-Bag (OOB) error?
Question 3 of 4
How does Random Forest calculate feature importance?
Question 4 of 4
How does increasing n_estimators affect bias and variance in Random Forest?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why does a Random Forest typically outperform a single Decision Tree?▼

Correct Answer: 100 trees trained on different bootstrap samples with random feature subsets — errors are partially independent, so averaging substantially reduces variance

Bootstrap sampling creates different errors per tree. Feature randomness prevents all trees relying on the same dominant feature. Independent errors cancel when averaged.

2What is the Out-of-Bag (OOB) error?▼

Correct Answer: Validation error estimated using examples not in each tree's bootstrap sample (~37% per tree) — a free cross-validation estimate without a separate split

Bootstrap selects ~63% unique examples per tree. The remaining ~37% are OOB — they serve as free validation. Averaging OOB errors across all trees gives a reliable performance estimate.

3How does Random Forest calculate feature importance?▼

Correct Answer: By measuring how much each feature reduces impurity across all trees and splits — features used at high-level splits affecting many examples have higher importance

Feature importance = average impurity decrease weighted by samples affected, across all trees. Note: can overestimate importance of high-cardinality features — use permutation importance for a more reliable estimate.

4How does increasing n_estimators affect bias and variance in Random Forest?▼

Correct Answer: High variance per individual tree — ensemble averaging reduces variance. More trees further reduces variance with diminishing returns; does not increase bias

Individual trees are high-variance. Random Forest reduces variance through averaging. More trees → less variance with diminishing returns after ~100-200 trees. Beyond ~500 trees, improvements are negligible.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next