Mastering Random Forest Regression: A Comprehensive Guide with Python Examples

CK CK 3788 
Created at  
1,094 0 0

A random forest is an ensemble learning method that combines the predictions from multiple decision trees to produce a more accurate and stable prediction. It is a type of supervised learning algorithm that can be used for both classification and regression tasks.

Every decision tree has high variance, but when we combine all of them in parallel then the resultant variance is low as each decision tree gets perfectly trained on that particular sample data, and hence the output doesn’t depend on one decision tree but on multiple decision trees. In the case of a classification problem, the final output is taken by using the majority voting classifier. In the case of a regression problem, the final output is the mean of all the outputs. This part is called Aggregation. 

Mastering Random Forest Regression: A Comprehensive Guide with Python Examples

 

Random Forest Regression in machine learning is an ensemble technique capable of performing both regression and classification tasks with the use of multiple decision trees and a technique called Bootstrap and Aggregation, commonly known as bagging. The basic idea behind this is to combine multiple decision trees in determining the final output rather than relying on individual decision trees. 

Random Forest has multiple decision trees as base learning models. We randomly perform row sampling and feature sampling from the dataset forming sample datasets for every model. This part is called Bootstrap.

We need to approach the Random Forest regression technique like any other machine learning technique.

  • Design a specific question or data and get the source to determine the required data.
  • Make sure the data is in an accessible format else convert it to the required format.
  • Specify all noticeable anomalies and missing data points that may be required to achieve the required data.
  • Create a machine-learning model.
  • Set the baseline model that you want to achieve
  • Train the data machine learning model.
  • Provide an insight into the model with test data
  • Now compare the performance metrics of both the test data and the predicted data from the model.
  • If it doesn’t satisfy your expectations, you can try improving your model accordingly or dating your data, or using another data modeling technique.
  • At this stage, you interpret the data you have gained and report accordingly. 
# Importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
# Generating synthetic dataset
X, y = make_regression(n_samples=1000, n_features=1, noise=10, random_state=42)
# Splitting dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Creating and training the Random Forest Regressor model
rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)
rf_regressor.fit(X_train, y_train)
# Predicting on the testing set
y_pred = rf_regressor.predict(X_test)
# Calculating Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
# Plotting the results
plt.figure(figsize=(10, 6))
plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.scatter(X_test, y_pred, color='red', label='Predicted')
plt.title('Random Forest Regression')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()

This code performs the following steps:

  1. Generates a synthetic dataset using make_regression.
  2. Splits the dataset into training and testing sets using train_test_split.
  3. Creates and trains a Random Forest Regressor model using RandomForestRegressor.
  4. Predicts on the testing set.
  5. Calculates the Mean Squared Error (MSE) using mean_squared_error.
  6. Plots the actual vs predicted values.

Below is the example data set

X (features):
[[ 0.9803]
 [-0.3673]
 [ 1.7859]
 ...
 [-0.5468]
 [-0.0486]
 [ 1.4225]]
y (target):
[ 68.67792672 -15.16765572 131.63145767 ... -23.54596341   1.50704555  91.64105671]	


Here's an example of Random Forest Regression in Python using scikit-learn library, with sample data containing three different variables, and including both training and testing phases:

# Import necessary libraries
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

# Sample data generation
np.random.seed(0)
n_samples = 1000
X1 = np.random.rand(n_samples) * 10
X2 = np.random.rand(n_samples) * 5
X3 = np.random.rand(n_samples) * 3
y = 2 * X1 + 3 * X2 - 4 * X3 + np.random.randn(n_samples) * 0.5  # Some linear combination with noise

# Combine features
X = np.column_stack((X1, X2, X3))

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Instantiate Random Forest Regression model
rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)

# Train the model
rf_regressor.fit(X_train, y_train)

# Make predictions on the testing set
y_pred = rf_regressor.predict(X_test)

# Calculate mean squared error
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)

In this example:

  • We generate sample data with three different variables (X1, X2, X3) and a target variable (y) which is a linear combination of these variables with some noise.
  • We split the data into training and testing sets using train_test_split.
  • We then instantiate the Random Forest Regression model with n_estimators=100, meaning we'll use 100 decision trees.
  • Next, we train the model using the training data.
  • We make predictions on the testing data.
  • Finally, we evaluate
Tags Ensemble Learning Ensemble Technique Random Forest Regression Facebook X
Comments 0
Similar posts
  1. Harnessing the Power of Random Forest Algorithm in Python
    657
  1. Python Web Programming based on Django from the Scratch
    366
  2. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    184
  3. How do I determine the client IP type in Python - IPv4 or IPv6
    760
  4. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,231
  5. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  6. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
  7. Dynamic DNS Made Easy: Building a Python-Based Solution
    793
  8. Milvus & FAISS: Decoding Their ML Synergy
    276
  9. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    376
  10. Forecasting with Linear Regression and KNN Regression in Python
    920
  11. Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction
    1,431
  12. Uvicorn, Gunicorn: Proving Your Production Prowess
    395
  13. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,154
  14. Harnessing the Power of Random Forest Algorithm in Python
    657
  15. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    632
  16. Simple Python Clustering Example based on the high school students' score
    339
  17. Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network
    799
  18. Memory Problems with Python Arrays? Discover Dask Array
    321
  19. Python Implementation of Linear Regression
    837
  20. Mastering Supervised Machine Learning with Python: A Comprehensive Guide
    1,054
  21. Mastering AI: A Beginner's Guide to Python Programming and Beyond
    1,031
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,733
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252