Random Forest Classifier using Scikit-learn

GeoSense ✅
2 min readMar 31

Random Forest is a popular ensemble learning method that can be used for classification and regression tasks. It builds multiple decision trees and aggregates their predictions to improve accuracy and reduce overfitting. Scikit-learn is a popular Python library for machine learning, including Random Forest Classifier.

Random Forest Classifier

Here’s an example of how to use Random Forest Classifier in Scikit-learn:

# importing required libraries 
# importing Scikit-learn library and datasets package
from sklearn import datasets

# Loading the iris plants dataset (classification)
iris = datasets.load_iris()
print(iris.target_names)
print(iris.feature_names)
['setosa' 'versicolor' 'virginica']
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
# dividing the datasets into two parts i.e. training datasets and test datasets
X, y = datasets.load_iris( return_X_y = True)

# Splitting arrays or matrices into random train and test subsets
from sklearn.model_selection import train_test_split
# i.e. 70 % training dataset and 30 % test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30)
# importing random forest classifier from assemble module
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
# creating dataframe of IRIS dataset
data = pd.DataFrame({"sepallength": iris.data[:, 0], "sepalwidth": iris.data[:, 1],
"petallength": iris.data[:, 2], "petalwidth": iris.data[:, 3],
"species": iris.target})
# printing the top 5 datasets in iris dataset
print(data.head())
 sepallength  sepalwidth  petallength  petalwidth  species
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
3 4.6 3.1 1.5 0.2 0
4 5.0 3.6 1.4 0.2 0
# creating a RF classifier
clf = RandomForestClassifier(n_estimators = 100)

# Training the model on the training dataset
# fit function is used to train the model using the training sets as parameters
clf.fit(X_train, y_train)

# performing predictions on the test…
GeoSense ✅

🌏 Remote sensing | 🛰️ Geographic Information Systems (GIS) | ℹ️ https://www.tnmthai.com/medium