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

Random Forest Hyperparameter Tuning in Python

Last Updated : 30 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 score among all the Machine Learning Algorithms. Since Machine Learning are classified into Supervised and Unsupervised Learning, we have two types of approach in Supervised Learning that is Regression and classification. Talking of Classification, let us consider one of the ensembles technique i.e., the Random Forest algorithm. While building a Classification model, we always think about what value should be assigned to the Hyperparameters. Hyperparameters are similar to parameters but the only difference is there is no one specific value to these Hyperparameters.

Since we are talking about Random Forest Hyperparameters, let us see what different Hyperparameters can be Tuned. 

Random Forest Hyperparameters

1. n_estimators

Random Forest is nothing but a set of trees. It is an extended version of the Decision Tree in a very optimized way. One issue here might arise is how many trees need to be created. n_estimator is the hyperparameter that defines the number of trees to be used in the model. The tree can also be understood as the sub-divisions. 

By default: n_estimators=100

2. max_features

In order to train the Machine learning model, the given dataset should contain multiple features/variables to predict the label/target. Max_features limits a count to select the maximum features in each tree. 

By default: max_features="sqrt" [available: ["sqrt", "log2", None}]

3. max_depth

A tree is incomplete without a split or child node. max_depth determines the maximum number of splits each tree can take. If the max_depth is too low, the model will be trained less and have a high bias, leading the model to underfit. In the same way, if the max_depth is high, the model learns too much and leads to high variance, leading the model to overfit.

By default: max_depth=None

4. max_leaf_nodes

We have a tree and know what max_depth is used for. Talking of a Tree, each tree is used to split into multiple nodes. But how many divisions of nodes should be done is specified by max_lead_nodes. max_leaf_nodes restricts the growth of each tree. 

By default: max_leaf_nodes = None;  (takes an unlimited number of nodes)

5. max_sample

Apart from the features, we have a large set of training datasets. max_sample determines how much of the dataset is given to each individual tree. 

By default: max_sample = None; (this means data.shape[0] is taken)

6. min_sample_split

Since ensemble algorithms are weak learners and are derived from strong learners, Random Forest which is a Weak Learner depends on Decision Tree decisions.  min_sample_split determines the minimum number of decision tree observations in any given node in order to split. 

By default: min_sample_split = 2 (this means every node has 2 subnodes)

For a more detailed article, you can check this:  Hyperparameters of Random Forest Classifier

Random Forest Hyperparameter Tuning in Python using Sklearn

Sklearn supports Hyperparameter Tuning algorithms that help to fine-tune the Machine learning models. In this article, we shall use two different Hyperparameter Tuning i.e., GridSearchCV and RandomizedSearchCV.

Import the required modules that are needed to fine-tune the Hyperparameters in Random Forest. 

Python3




from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV,\
RandomizedSearchCV


Load the Dataset

Python3




data = pd.read_csv(
    "100DaysOfML/main/Day14%3A%20Logistic_Regression"
    "_Metric_and_practice/heart_disease.csv")
data.head(7)


Output:

First five rows of the dataset

First five rows of the dataset

Python3




data['target'].value_counts()


Output:

1    165
0    138
Name: target, dtype: int64

Prepare and Split the Data

We shall consider all the columns as our input i.e., features. And the target column will act as the label that we need to predict. Using train_test_split we split out the test size and train size by 25:75 percent. 

Python3




X = data.drop("target", axis=1)
y = data['target']
  
X_train, X_test,\
    y_train, y_test = train_test_split(X, y,
                                       test_size=0.25,
                                       random_state=42)
X_train.shape, X_test.shape


Output:

((227, 13), (76, 13))

Build Random Forest Model

First, we will train the model with default Random Forest Classifier Hyperparameters. 

Python3




model = RandomForestClassifier()
model.fit(X_train, y_train)
  
# predict the mode
y_pred = model.predict(X_test)
  
# performance evaluatio metrics
print(classification_report(y_pred, y_test))


Output:

Classification report for the Random Forest Model

Classification report for the Random Forest Model

Python3




param_grid = {
    'n_estimators': [25, 50, 100, 150],
    'max_features': ['sqrt', 'log2', None],
    'max_depth': [3, 6, 9],
    'max_leaf_nodes': [3, 6, 9],
}


Note: Hyperparameter Tuning doesn’t work all the time. Sometimes the Default Hyperparameters are also considered to be the best estimators. 

Hyperparameter Tuning- GridSearchCV

First, let’s use GridSearchCV to obtain the best parameters for the model. For that, we will pass RandomFoestClassifier() instance to the model and then fit the GridSearchCV using the training data to find the best parameters.

Python3




grid_search = GridSearchCV(RandomForestClassifier(),
                           param_grid=param_grid)
grid_search.fit(X_train, y_train)
print(grid_search.best_estimator_)


Output:

Parameters obtained by using GridSearchCV

Parameters obtained by using GridSearchCV

Update the Model

Now we will update the parameters of the model by those which are obtained by using GridSearchCV.

Python3




model_grid = RandomForestClassifier(max_depth=9,
                                    max_features="log2",
                                    max_leaf_nodes=9,
                                    n_estimators=25)
model_grid.fit(X_train, y_train)
y_pred_grid = model.predict(X_test)
print(classification_report(y_pred_grid, y_test))


Output:

Classification report for the Random Forest Model

Classification report for the Random Forest Model

Hyperparameter Tuning- RandomizedSearchCV

Now let’s use RandomizedSearchCV to obtain the best parameters for the model. For that, we will pass RandomFoestClassifier() instance to the model and then fit the RandomizedSearchCV using the training data to find the best parameters.

Python3




random_search = RandomizedSearchCV(RandomForestClassifier(),
                                   param_grid)
random_search.fit(X_train, y_train)
print(random_search.best_estimator_)


Output:

Parameters obtained by using RandomizedSearchCV

Parameters obtained by using RandomizedSearchCV

Update the model

Now we will update the parameters of the model by those which are obtained by using RandomizedSearchCV.

Python3




model_random = RandomForestClassifier(max_depth=3,
                                      max_features='log2',
                                      max_leaf_nodes=6,
                                      n_estimators=100)
model_random.fit(X_train, y_train)
y_pred_rand = model.predict(X_test)
print(classification_report(y_pred_rand, y_test))


Output:

Classification report for the Random Forest Model

Classification report for the Random Forest Model



Similar Reads

SVM Hyperparameter Tuning using GridSearchCV | ML
A Machine Learning model is defined as a mathematical model with a number of parameters that need to be learned from the data. However, there are some parameters, known as Hyperparameters and those cannot be directly learned. They are commonly chosen by humans based on some intuition or hit and trial before the actual training begins. These paramet
4 min read
Cross-validation and Hyperparameter tuning of LightGBM Model
In a variety of industries, including finance, healthcare, and marketing, machine learning models have become essential for resolving challenging real-world issues. Gradient boosting techniques have become incredibly popular among the myriad of machine learning algorithms due to their remarkable prediction performance. Due to its speed and effectiv
14 min read
CatBoost Cross-Validation and Hyperparameter Tuning
CatBoost is a powerful gradient-boosting algorithm of machine learning that is very popular for its effective capability to handle categorial features of both classification and regression tasks. To maximize the potential of CatBoost, it's essential to fine-tune its hyperparameters which can be done by Cross-validation. Cross-validation is a crucia
11 min read
Hyperparameter tuning
A Machine Learning model is defined as a mathematical model with several parameters that need to be learned from the data. By training a model with existing data, we can fit the model parameters. However, there is another kind of parameter, known as Hyperparameters, that cannot be directly learned from the regular training process. They are usually
11 min read
Hyperparameter tuning using GridSearchCV and KerasClassifier
Hyperparameter tuning is done to increase the efficiency of a model by tuning the parameters of the neural network. Some scikit-learn APIs like GridSearchCV and RandomizedSearchCV are used to perform hyper parameter tuning. In this article, you'll learn how to use GridSearchCV to tune Keras Neural Networks hyper parameters. Approach: We will wrap K
2 min read
How to tune a Decision Tree in Hyperparameter tuning
Decision trees are powerful models extensively used in machine learning for classification and regression tasks. The structure of decision trees resembles the flowchart of decisions helps us to interpret and explain easily. However, the performance of decision trees highly relies on the hyperparameters, selecting the optimal hyperparameter can sign
14 min read
Hyperparameter Tuning in Linear Regression
Linear regression is one of the simplest and most widely used algorithms in machine learning. Despite its simplicity, it can be quite powerful, especially when combined with proper hyperparameter tuning. Hyperparameter tuning is the process of tuning a machine learning model's parameters to achieve optimal results. This article will delve into the
7 min read
Hyperparameter tuning SVM parameters using Genetic Algorithm
The performance support Vector Machines (SVMs) are heavily dependent on hyperparameters such as the regularization parameter (C) and the kernel parameters (gamma for RBF kernel). Genetic Algorithms (GAs) leverage evolutionary principles to search for optimal hyperparameter values. This article explores the use of Genetic Algorithms for tuning SVM p
9 min read
HyperParameter Tuning: Fixing Overfitting in Neural Networks
Overfitting is a pervasive problem in neural networks, where the model becomes too specialized to the training data and fails to generalize well to new, unseen data. This issue can be addressed through hyperparameter tuning, which involves adjusting various parameters to optimize the performance of the model. In this article, we will delve into the
6 min read
Hyperparameter tuning with Ray Tune in PyTorch
Hyperparameter tuning is a crucial step in the machine learning pipeline that can significantly impact the performance of a model. Choosing the right set of hyperparameters can be the difference between an average model and a highly accurate one. Ray Tune is an industry-standard tool for distributed hyperparameter tuning that integrates seamlessly
8 min read
Hyperparameter Tuning with R
In R Language several techniques and packages can be used to optimize these hyperparameters, leading to better, more reliable models. in this article, we will discuss all the techniques and packages for Hyperparameter Tuning with R. What are Hyperparameters?Hyperparameters are the settings that control how a machine-learning model learns from data.
5 min read
Hyperparameter tuning with Optuna in PyTorch
Hyperparameter tuning is a critical step in the machine learning pipeline, often determining the success of a model. Optuna is a powerful and flexible framework for hyperparameter optimization, designed to automate the search for optimal hyperparameters. When combined with PyTorch, a popular deep learning library, Optuna can significantly enhance m
5 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 Regression in Python
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 LearningEnsemble learning is a machine learning tech
11 min read
Comparing Randomized Search and Grid Search for Hyperparameter Estimation in Scikit Learn
Hyperparameters are the parameters that determine the behavior and performance of a machine-learning model. These parameters are not learned during training but are instead set prior to training. The process of finding the optimal values for these hyperparameters is known as hyperparameter optimization, and it is an important step in the developmen
8 min read
Hyperparameter Optimization Based on Bayesian Optimization
In this article we explore what is hyperparameter optimization and how can we use Bayesian Optimization to tune hyperparameters in various machine learning models to obtain better prediction accuracy. Before we dive into the how's of implementing Bayesian Optimization, let us learn what is meant by hyperparameters and hyperparameter optimization. H
7 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
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
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