The Wayback Machine - https://web.archive.org/web/20241001065411/https://www.geeksforgeeks.org/random-forest-regression-in-python/
Open In App

Random Forest Regression in Python

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Random Forest Regression is a versatile machine-learning technique for predicting numerical values. It combines the predictions of multiple decision trees to reduce overfitting and improve accuracy. Python’s machine-learning libraries make it easy to implement and optimize this approach.

Ensemble Learning

Ensemble learning is a machine learning technique that combines the predictions from multiple models to create a more accurate and stable prediction. It is an approach that leverages the collective intelligence of multiple models to improve the overall performance of the learning system.

Types of Ensemble Methods

There are various types of ensemble learning methods, including:

  1. Bagging (Bootstrap Aggregating): This method involves training multiple models on random subsets of the training data. The predictions from the individual models are then combined, typically by averaging.
  2. Boosting: This method involves training a sequence of models, where each subsequent model focuses on the errors made by the previous model. The predictions are combined using a weighted voting scheme.
  3. Stacking: This method involves using the predictions from one set of models as input features for another model. The final prediction is made by the second-level model.

Random Forest

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. 

Random Forest Regression Model Working

Random Forest Regression Model Working

What is Random Forest Regression?

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. 

Random Forest Regression in Python

We will be using a similar sample technique in the below example. Below is a step-by-step sample implementation of Random Forest Regression, on the dataset that can be downloaded here- https://bit.ly/417n3N5

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • RandomForestRegressor – This is the regression model that is based upon the Random Forest model or the ensemble learning that we will be using in this article using the sklearn library.
  • sklearn: This library is the core machine learning library in Python. It provides a wide range of tools for preprocessing, modeling, evaluating, and deploying machine learning models.
  • LabelEncoder: This class is used to encode categorical data into numerical values.
  • KNNImputer: This class is used to impute missing values in a dataset using a k-nearest neighbors approach.
  • train_test_split: This function is used to split a dataset into training and testing sets.
  • StandardScaler: This class is used to standardize features by removing the mean and scaling to unit variance.
  • f1_score: This function is used to evaluate the performance of a classification model using the F1 score.
  • RandomForestRegressor: This class is used to train a random forest regression model.
  • cross_val_score: This function is used to perform k-fold cross-validation to evaluate the performance of a model

Step-1: Import Libraries

Here we are importing all the necessary libraries required.

Python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
import warnings

from sklearn.preprocessing import LabelEncoder
from sklearn.impute import KNNImputer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import f1_score
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score

warnings.filterwarnings('ignore')

Step-2: Import Dataset

Now let’s load the dataset in the panda’s data frame. For better data handling and leveraging the handy functions to perform complex tasks in one go.

Python
df= pd.read_csv('Salaries.csv')
print(df)

Output:

            Position  Level   Salary
0 Business Analyst 1 45000
1 Junior Consultant 2 50000
2 Senior Consultant 3 60000
3 Manager 4 80000
4 Country Manager 5 110000
5 Region Manager 6 150000
6 Partner 7 200000
7 Senior Partner 8 300000
8 C-level 9 500000
9 CEO 10 1000000


Here the .info() method provides a quick overview of the structure, data types, and memory usage of the dataset.

Python
df.info()

Output:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Position 10 non-null object
1 Level 10 non-null int64
2 Salary 10 non-null int64
dtypes: int64(2), object(1)
memory usage: 372.0+ bytes

Step-3: Data Preparation

Here the code will extracts two subsets of data from the Dataset and stores them in separate variables.

  • Extracting Features: It extracts the features from the DataFrame and stores them in a variable named X.
  • Extracting Target Variable: It extracts the target variable from the DataFrame and stores it in a variable named y.
Python
# Assuming df is your DataFrame
X = df.iloc[:,1:2].values  #features
y = df.iloc[:,2].values  # Target variable

Step-4: Random Forest Regressor Model

The code processes categorical data by encoding it numerically, combines the processed data with numerical data, and trains a Random Forest Regression model using the prepared data.

Python
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder

 Check for and handle categorical variables
label_encoder = LabelEncoder()
x_categorical = df.select_dtypes(include=['object']).apply(label_encoder.fit_transform)
x_numerical = df.select_dtypes(exclude=['object']).values
x = pd.concat([pd.DataFrame(x_numerical), x_categorical], axis=1).values

# Fitting Random Forest Regression to the dataset
regressor = RandomForestRegressor(n_estimators=10, random_state=0, oob_score=True)

# Fit the regressor with x and y data
regressor.fit(x, y)

Step-5: Make predictions and Evaluation

The code evaluates the trained Random Forest Regression model:

  • out-of-bag (OOB) score, which estimates the model’s generalization performance.
  • Makes predictions using the trained model and stores them in the ‘predictions’ array.
  • Evaluates the model’s performance using the Mean Squared Error (MSE) and R-squared (R2) metrics.

Out of Bag Score in RandomForest

Bag score or OOB score is the type of validation technique that is mainly used in bagging algorithms to validate the bagging algorithm. Here a small part of the validation data is taken from the mainstream of the data and the predictions on the particular validation data are done and compared with the other results.

The main advantage that the OOB score offers is that here the validation data is not seen by the bagging algorithm and that is why the results on the OOB score are the true results that indicated the actual performance of the bagging algorithm.

To get the OOB score of the particular Random Forest algorithm, one needs to set the value “True” for the OOB_Score parameter in the algorithm.

Python
# Evaluating the model
from sklearn.metrics import mean_squared_error, r2_score

# Access the OOB Score
oob_score = regressor.oob_score_
print(f'Out-of-Bag Score: {oob_score}')

# Making predictions on the same data or new data
predictions = regressor.predict(x)

# Evaluating the model
mse = mean_squared_error(y, predictions)
print(f'Mean Squared Error: {mse}')

r2 = r2_score(y, predictions)
print(f'R-squared: {r2}')

Output:

Out-of-Bag Score: 0.644879832593859
Mean Squared Error: 2647325000.0
R-squared: 0.9671801245316117

Step-6: Visualization

Now let’s visualize the results obtained by using the RandomForest Regression model on our salaries dataset.

  • Creates a grid of prediction points covering the range of the feature values.
  • Plots the real data points as blue scatter points.
  • Plots the predicted values for the prediction grid as a green line.
  • Adds labels and a title to the plot for better understanding.
Python
import numpy as np
X_grid = np.arange(min(X),max(X),0.01)
X_grid = X_grid.reshape(len(X_grid),1) 
  
plt.scatter(X,y, color='blue') #plotting real points
plt.plot(X_grid, regressor.predict(X_grid),color='green') #plotting for predict points
  
plt.title("Random Forest Regression Results")
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

Output: 

Screenshot-2023-12-04-101235

Step-7: Visualizing a Single Decision Tree from the Random Forest Model

The code visualizes one of the decision trees from the trained Random Forest model. Plots the selected decision tree, displaying the decision-making process of a single tree within the ensemble.

Python
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt

# Assuming regressor is your trained Random Forest model
# Pick one tree from the forest, e.g., the first tree (index 0)
tree_to_plot = regressor.estimators_[0]

# Plot the decision tree
plt.figure(figsize=(20, 10))
plot_tree(tree_to_plot, feature_names=df.columns.tolist(), filled=True, rounded=True, fontsize=10)
plt.title("Decision Tree from Random Forest")
plt.show()

Output:

Screenshot-2023-12-05-111140Applications of Random Forest Regression

The Random forest regression has a wide range of real-world problems, including:

  • Predicting continuous numerical values: Predicting house prices, stock prices, or customer lifetime value.
  • Identifying risk factors: Detecting risk factors for diseases, financial crises, or other negative events.
  • Handling high-dimensional data: Analyzing datasets with a large number of input features.
  • Capturing complex relationships: Modeling complex relationships between input features and the target variable.

Advantages of Random Forest Regression

  • It is easy to use and less sensitive to the training data compared to the decision tree.
  • It is more accurate than the decision tree algorithm.
  • It is effective in handling large datasets that have many attributes.
  • It can handle missing data, outliers, and noisy features.

Disadvantages of Random Forest Regression

  • The model can also be difficult to interpret.
  • This algorithm may require some domain expertise to choose the appropriate parameters like the number of decision trees, the maximum depth of each tree, and the number of features to consider at each split.
  • It is computationally expensive, especially for large datasets.
  • It may suffer from overfitting if the model is too complex or the number of decision trees is too high.

Conclusion

Random Forest Regression has become a powerful tool for continuous prediction tasks, with advantages over traditional decision trees. Its capability to handle high-dimensional data, capture complex relationships, and reduce overfitting has made it a popular choice for a variety of applications. Python’s scikit-learn library enables the implementation, optimization, and evaluation of Random Forest Regression models, making it an accessible and effective technique for machine learning practitioners.

Frequently Asked Question(FAQ’s)

1. What is Random Forest Regression Python?

Random Forest Regression Python is an ensemble learning method that uses multiple decision trees to make predictions. It is a powerful and versatile algorithm that is well-suited for regression tasks.

2. What is the use of random forest regression?

Random Forest Regression can be used to predict a variety of target variables, including prices, sales, customer churn, and more. It is a robust algorithm that is not easily overfitted, making it a good choice for real-world applications.

3. What is the difference between random forest and regression?

Random Forest is an ensemble learning method, while regression is a type of supervised learning algorithm. Random Forest uses multiple decision trees to make predictions, while regression uses a single model to make predictions.

4. How do you tune the hyperparameters of Random Forest Regression?

There are several methods for tuning the hyperparameters of Random Forest Regression, such as:

  • Grid search: Grid search involves systematically trying different combinations of hyperparameter values to find the best combination.
  • Random search: Random search randomly samples different combinations of hyperparameter values to find a good combination.

5. Why is random forest better than regression?

Random Forest is generally more accurate and robust than regression. It is also less prone to overfitting, which means that it is more likely to generalize well to new data.




Previous Article
Next Article

Similar Reads

Logistic Regression Vs Random Forest Classifier
A statistical technique called logistic regression is used to solve problems involving binary classification, in which the objective is to predict a binary result (such as yes/no, true/false, or 0/1) based on one or more predictor variables (also known as independent variables, features, or predictors). Based on the values of the predictor variable
7 min read
Regression with Random Forest on Imbalanced data in R
Random Forest is a versatile and powerful machine learning algorithm that can be used for regression tasks, especially when dealing with complex and nonlinear relationships in data. However, when the dataset is imbalanced — meaning one outcome class is significantly more frequent than the others — special considerations need to be taken to ensure t
6 min read
Why Do We Pick Random Features in Random Forest?
Answer: We pick random features in a Random Forest to increase diversity among the trees, reducing overfitting and improving model robustness.In Random Forest, the selection of random features for each decision tree is a fundamental strategy to enhance the model's performance. This technique introduces variety in the trees that comprise the forest,
2 min read
How to Solve Overfitting in Random Forest in Python Sklearn?
In this article, we are going to see the how to solve overfitting in Random Forest in Sklearn Using Python. What is overfitting?Overfitting is a common phenomenon you should look out for any time you are training a machine learning model. Overfitting happens when a model learns the pattern as well as the noise of the data on which the model is trai
5 min read
Random Forest Hyperparameter Tuning in Python
In this article, we shall implement Random Forest Hyperparameter Tuning in Python using Sci-kit Library. Sci-kit aka Sklearn is a Machine Learning library that supports many Machine Learning Algorithms, Pre-processing Techniques, Performance Evaluation metrics, and many other algorithms. Ensemble Techniques are considered to give a good accuracy sc
5 min read
Hyperparameters of Random Forest Classifier
In this article, we are going to learn about different hyperparameters that exist in a Random Forest Classifier. We have already learnt about the implementation of Random Forest Classifier using scikit-learn library in the article https://www.geeksforgeeks.org/random-forest-classifier-using-scikit-learn/. Hyperparameters are configurations that can
4 min read
Differences between Random Forest and AdaBoost
Random Forest Algorithm is a commonly used machine learning algorithm that combines the output of multiple Decision Trees to achieve a single result. It handles both classification and regression problems as it combines the simplicity of decision trees with flexibility leading to significant improvements in accuracy. AdaBoost Algorithm (Adaptive Bo
4 min read
Calculate ROC AUC for Classification Algorithm Such as Random Forest
Receiver Operating Characteristic (ROC) curves and Area Under the Curve (AUC) are popular evaluation metrics for classification algorithms, In this article, we will discuss how to calculate the ROC AUC for a Random Forest classifier. ROC AUC is a metric that quantifies the ability of a binary classifier to distinguish between positive and negative
8 min read
Random Forest for Time Series Forecasting using R
Random Forest is an ensemble machine learning method that can be used for time series forecasting. It is based on decision trees and combines multiple decision trees to make more accurate predictions. Here's a complete explanation along with an example of using Random Forest for time series forecasting in R. Time Series ForecastingTime series forec
7 min read
Random Forest Classifier using Scikit-learn
In this article, we will see how to build a Random Forest Classifier using the Scikit-Learn library of Python programming language and to do this, we use the IRIS dataset which is quite a common and famous dataset. Random ForestThe Random forest or Random Decision Forest is a supervised Machine learning algorithm used for classification, regression
8 min read
How do you Make a Prediction with Random Forest in R?
In the field of data science, random forests have become a tool. They are known for their ability to handle types of data prevent overfitting and provide interpretability. In this article, we shall take a look at the procedure for making forecasts with forests in R Programming Language and show how you can use an existing Iris dataset to demonstrat
10 min read
What is the Need of XGBoost and Random Forest?
Answer: XGBoost and Random Forest are ensemble learning algorithms that enhance predictive accuracy and handle complex relationships in machine learning by leveraging multiple decision trees.Random Forest: High Predictive Accuracy:Random Forest is an ensemble learning method that builds multiple decision trees and combines their predictions. This e
3 min read
What are the Advantages and Disadvantages of Random Forest?
Random Forest Algorithm is a strong and popular machine learning method with a number of advantages as well as disadvantages. It is an efficient method for handling a range of tasks, such as feature selection, regression, and classification. It works with the aid of constructing an ensemble of choice timber and combining their predictions. In this
6 min read
Difference Between Random Forest and Decision Tree
Choosing the appropriate model is crucial when it comes to machine learning. A model that functions properly with one kind of dataset might not function well with another. Both Random Forest and Decision Tree are strong algorithms for applications involving regression and classification. The aim of the article is to cover the distinction between de
3 min read
Random Forest vs Support Vector Machine vs Neural Network
Machine learning boasts diverse algorithms, each with its strengths and weaknesses. Three prominent are – Random Forest, Support Vector Machines (SVMs), and Neural Networks – stand out for their versatility and effectiveness. But when do you we choose one over the others? In this article, we'll delve into the key differences between these three alg
5 min read
Bagging and Random Forest for Imbalanced Classification
Ensemble learning techniques like bagging and random forests have gained prominence for their effectiveness in handling imbalanced classification problems. In this article, we will delve into these techniques and explore their applications in mitigating the impact of class imbalance. Classification problems are fundamental to machine learning and f
8 min read
Random Forest for Image Classification Using OpenCV
Random Forest is a machine learning algorithm that uses multiple decision trees to achieve precise results in classification and regression tasks. It resembles the process of choosing the best path amidst multiple options. OpenCV, an open-source library for computer vision and machine learning tasks, is used to explore and extract insights from vis
8 min read
The Effects of the Depth and Number of Trees in a Random Forest
Random forests, powerful ensembles of decision trees, benefit from tuning key parameters like tree depth and number of trees for optimal prediction and data modeling. In this article, we will be discussing the effects of the depth and the number of trees in a random forest model. Table of Content Random ForestUnderstanding the Impact of Depth and N
8 min read
When to use Random Forest over SVM and vice versa?
Choosing the best algorithm for a given task might be a challenge for machine learning enthusiasts. Random Forest and Support Vector machines (SVM) are two well-liked options that are effective on their own and can handle various kinds of problems. In this post, we'll examine the ideas behind these algorithms, provide good examples with output scre
5 min read
How to fit categorical data types for random forest classification?
Categorical variables are an essential component of many datasets, representing qualitative characteristics rather than numerical values. While random forest classification is a powerful machine-learning technique, it typically requires numerical input data. Therefore, encoding categorical variables into a suitable format is a crucial step in prepa
9 min read
Gradient Boosting vs Random Forest
Gradient Boosting Trees (GBT) and Random Forests are both popular ensemble learning techniques used in machine learning for classification and regression tasks. While they share some similarities, they have distinct differences in terms of how they build and combine multiple decision trees. The article aims to discuss the key differences between Gr
7 min read
Difference Between Random Forest and XGBoost
Random Forest and XGBoost are both powerful machine learning algorithms widely used for classification and regression tasks. While they share some similarities in their ensemble-based approaches, they differ in their algorithmic techniques, handling of overfitting, performance, flexibility, and parameter tuning. In this tutorial, we will understand
6 min read
Handling Missing Values with Random Forest
Data imputation is a critical challenge in machine learning, with missing values impacting statistical modelling. Random Forest, an ensemble learning method, is a robust solution for accurate predictions, particularly in healthcare. It can handle classification and regression problems, and it is more nuanced than traditional methods. It can handle
10 min read
How to Visualize a Decision Tree from a Random Forest
Random Forest is a versatile and powerful machine learning algorithm used for both classification and regression tasks. It belongs to the ensemble learning method, which involves combining multiple individual decision trees to create a more robust and accurate model. In this article, we will discuss how we can visualize individual decision tree in
5 min read
IBM HR Analytics on Employee Attrition & Performance using Random Forest Classifier
Attrition is a problem that impacts all businesses, irrespective of geography, industry and size of the company. It is a major problem to an organization, and predicting turnover is at the forefront of the needs of Human Resources (HR) in many organizations. Organizations face huge costs resulting from employee turnover. With advances in machine le
5 min read
Interpreting Random Forest Classification Results
Random Forest is a powerful and versatile machine learning algorithm that excels in both classification and regression tasks. It is an ensemble learning method that constructs multiple decision trees during training and outputs the class that is the mode of the classes (for classification) or mean prediction (for regression) of the individual trees
6 min read
Feature Selection Using Random Forest
Feature selection is a crucial step in building machine learning models. It involves selecting the most important features from your dataset that contribute to the predictive power of the model. Random Forest, an ensemble learning method, is widely used for feature selection due to its inherent ability to rank features based on their importance. Th
4 min read
Feature Selection Using Random forest Classifier
Feature selection is a crucial step in the machine learning pipeline that involves identifying the most relevant features for building a predictive model. One effective method for feature selection is using a Random Forest classifier, which provides insights into feature importance. In this article, we will explore how to use a Random Forest classi
5 min read
How to Calculate the OOB of Random Forest in R?
Random Forest is a versatile machine-learning algorithm that builds multiple decision trees and merges them together to get a more accurate and stable prediction. One of the advantages of Random Forest is that it provides an internal error estimation known as the Out-of-Bag (OOB) error. This article will guide you through calculating the OOB error
4 min read
How to Create a 2D Partial Dependence Plot on a Trained Random Forest Model in R
Random Forest, a powerful ensemble learning algorithm, is widely used for regression and classification tasks due to its robustness and ability to handle complex data. However, understanding how individual features influence the model's predictions can be challenging. Partial Dependence Plots (PDPs) provide a valuable tool for visualizing the relat
3 min read