You can download this code by clicking the button below.
This code is now available for download.
This function uses the Random Forest algorithm to classify the given data and returns the accuracy of the model. First, the data is split into training and testing sets, then a Random Forest classifier is initialized, trained, and predictions are made on the test set, finally the accuracy is calculated.
Technology Stack : scikit-learn
Code Type : Machine learning classification
Code Difficulty : Intermediate
def random_forest_classification(X, y):
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize the Random Forest Classifier
clf = RandomForestClassifier(n_estimators=100, random_state=42)
# Train the model
clf.fit(X_train, y_train)
# Predict the labels for the test set
y_pred = clf.predict(X_test)
# Calculate the accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
return accuracy