Random Forest Classification Accuracy Calculation

  • Share this:

Code introduction


This function uses the RandomForestClassifier from scikit-learn to train on the training data, make predictions on the test data, and finally calculate the accuracy of the predictions.


Technology Stack : scikit-learn

Code Type : Machine learning

Code Difficulty : Intermediate


                
                    
def random_forest_classification(X_train, y_train, X_test):
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import accuracy_score

    # Initialize the RandomForestClassifier
    clf = RandomForestClassifier()

    # Train the model
    clf.fit(X_train, y_train)

    # Predict the labels for the test set
    predictions = clf.predict(X_test)

    # Calculate the accuracy of the model
    accuracy = accuracy_score(y_test, predictions)

    return accuracy                
              
Tags: