Random Forest Classification Accuracy Calculator

  • Share this:

Code introduction


This function uses a random forest classifier for classification and calculates the classification accuracy. It first splits the dataset into training and testing sets, then creates a random forest classifier instance for training, and finally predicts on the test set and calculates the accuracy.


Technology Stack : Scikit-learn

Code Type : Machine learning classification

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 dataset 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)
    
    # Create a RandomForestClassifier instance
    clf = RandomForestClassifier(n_estimators=100, random_state=42)
    
    # Train the classifier
    clf.fit(X_train, y_train)
    
    # Make predictions
    y_pred = clf.predict(X_test)
    
    # Calculate accuracy
    accuracy = accuracy_score(y_test, y_pred)
    
    return accuracy                
              
Tags: