You can download this code by clicking the button below.
This code is now available for download.
This function trains an XGBoost model for classification or regression. It randomly selects model parameters and trains the model using random sample training data.
Technology Stack : XGBoost, NumPy
Code Type : XGBoost model training function
Code Difficulty : Intermediate
import xgboost as xgb
import numpy as np
import random
def random_xgb_model(X, y):
# Define the parameters for the XGBoost model
params = {
'max_depth': random.choice([3, 5, 7, 9, 11]),
'eta': random.uniform(0.01, 0.3),
'subsample': random.uniform(0.5, 1.0),
'colsample_bytree': random.uniform(0.5, 1.0),
'objective': 'binary:logistic' if random.choice([True, False]) else 'reg:squarederror'
}
# Create the XGBoost DMatrix
dtrain = xgb.DMatrix(X, label=y)
# Train the model
model = xgb.train(params, dtrain, num_boost_round=10)
return model