Random Forest Classification Accuracy Calculation

  • Share this:

Code introduction


This function uses the random forest algorithm to classify the given data and returns the accuracy on the test set.


Technology Stack : scikit-learn

Code Type : Machine learning

Code Difficulty : Intermediate


                
                    
def random_forest_classification(data, target, test_size=0.2):
    from sklearn.model_selection import train_test_split
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.metrics import accuracy_score

    # Splitting the dataset into training and testing sets
    X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=test_size, random_state=42)

    # Creating a random forest classifier
    clf = RandomForestClassifier(n_estimators=100, random_state=42)

    # Training the classifier
    clf.fit(X_train, y_train)

    # Making predictions on the test set
    y_pred = clf.predict(X_test)

    # Calculating the accuracy of the model
    accuracy = accuracy_score(y_test, y_pred)

    return accuracy                
              
Tags: