Random Forest Classification Accuracy Calculation

  • Share this:

Code introduction


This function uses a Random Forest classifier to train the training data, predicts on the test data, and finally calculates and returns the accuracy of the prediction.


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
    
    # Create a Random Forest Classifier
    clf = RandomForestClassifier(n_estimators=100, random_state=0)
    
    # Train the model using the training sets
    clf.fit(X_train, y_train)
    
    # Predict the response for test dataset
    y_pred = clf.predict(X_test)
    
    # Calculate the accuracy of the model
    accuracy = accuracy_score(y_test, y_pred)
    
    return accuracy                
              
Tags: