Random Forest Classification and Accuracy Evaluation

  • Share this:

Code introduction


This function uses the random forest algorithm to classify the training data and evaluate its accuracy on the test data.


Technology Stack : Scikit-learn

Code Type : Machine learning

Code Difficulty : Intermediate


                
                    
def random_forest_classification(X_train, y_train, X_test, n_estimators=100, max_depth=None):
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import accuracy_score
    
    # Initialize the RandomForestClassifier
    clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth)
    
    # Train the model
    clf.fit(X_train, y_train)
    
    # Make predictions on the test data
    predictions = clf.predict(X_test)
    
    # Calculate the accuracy of the model
    accuracy = accuracy_score(y_test, predictions)
    
    return accuracy                
              
Tags: