XGBoost Classification Model Accuracy Evaluation

  • Share this:

Code introduction


This function uses the XGBoost library to train a classification model and evaluates its accuracy on a test set.


Technology Stack : XGBoost, NumPy, Pandas

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import xgboost as xgb
import numpy as np
import pandas as pd

def predict_accuracy(X_train, y_train, X_test, y_test):
    # Create a DMatrix for training and testing data
    dtrain = xgb.DMatrix(X_train, label=y_train)
    dtest = xgb.DMatrix(X_test, label=y_test)
    
    # Define the parameters for the XGBoost model
    params = {
        'max_depth': 3,
        'eta': 0.1,
        'objective': 'binary:logistic',
        'eval_metric': 'logloss'
    }
    
    # Train the model
    bst = xgb.train(params, dtrain)
    
    # Predict on the test set
    y_pred = bst.predict(dtest)
    
    # Calculate the accuracy of the predictions
    accuracy = np.mean(y_pred == y_test)
    
    return accuracy