Random Forest Classification Accuracy Calculation

  • Share this:

Code introduction


This function uses a random forest classifier to classify the given features and labels and returns the classification accuracy.


Technology Stack : scikit-learn

Code Type : The type of code

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 RandomForestClassifier
    classifier = RandomForestClassifier(n_estimators=100, random_state=42)

    # Train the classifier
    classifier.fit(X_train, y_train)

    # Make predictions on the test set
    y_pred = classifier.predict(X_test)

    # Calculate the accuracy of the classifier
    accuracy = accuracy_score(y_test, y_pred)

    return accuracy                
              
Tags: