If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's an example of how you can implement a Random Forest classifier using Python and the scikit-learn
library for a classification task:
pythonCopy code
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score # Load the Iris dataset (you can replace this with your own 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 and train the Random Forest classifier model = RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X_train, y_train) # Make predictions on the test set y_pred = model.predict(X_test) # Calculate accuracy accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}")
This code snippet demonstrates the following steps:
sklearn
modules).RandomForestClassifier
model from scikit-learn
with 100 decision trees.You can customize the hyperparameters of the Random Forest, such as the number of estimators (decision trees), the maximum depth of trees, and other settings. Random Forest is an ensemble method that combines multiple decision trees to improve overall performance and reduce overfitting.
Similarly, you can adapt the code for regression tasks using RandomForestRegressor
from scikit-learn
. Remember to replace the dataset loading and preprocessing steps with your own data if needed.
Comments: 0