Training and Predicting with XGBoost DMatrix

  • Share this:

Code introduction


This function uses the DMatrix class from the XGBoost library to initialize the data, then uses this data to train an XGBoost model, and finally returns the model's predictions on the training data.


Technology Stack : XGBoost, Numpy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import xgboost as xgb
import numpy as np

def random_xgb_model(X, y):
    # Initialize a DMatrix from the data
    dtrain = xgb.DMatrix(X, label=y)
    
    # 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 same data (for demonstration purposes)
    y_pred = bst.predict(dtrain)
    
    return y_pred                
              
Tags: