Dev Duniya
Mar 19, 2025
Random Forest is a powerful ensemble learning method that combines multiple decision trees to create a more robust and accurate prediction model. It's a versatile algorithm used for both classification and regression tasks.



from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Load the iris dataset
iris = load_iris()
X = iris.data
y = iris.target
# 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)
# Create a Random Forest classifier
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# Train the model
rf_classifier.fit(X_train, y_train)
# Make predictions
y_pred = rf_classifier.predict(X_test)
# Evaluate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
Import necessary libraries:
RandomForestClassifier: Imports the Random Forest classifier from scikit-learn.load_iris: Loads the iris dataset.train_test_split: Splits the data into training and testing sets.accuracy_score: Calculates the accuracy of the model.Load and prepare the data:
Create and train the Random Forest model:
RandomForestClassifier object with the desired number of trees (n_estimators).fit() method with the training data.Make predictions and evaluate:
This example demonstrates a basic implementation of the Random Forest algorithm. You can experiment with different hyperparameters (e.g., number of trees, maximum depth of trees) to further optimize the model's performance.