To fit an XGBoost model with grid search over parameters in Python, you can use the GridSearchCV
class from the sklearn
library. Here's an example:
main.py905 chars31 lines
In this example, we define the param_grid
dictionary with the hyperparameters we want to tune. We then create an XGBoost classifier using xgb.XGBClassifier()
.
Next, we create a GridSearchCV
object and pass it the XGBoost classifier, the parameter grid, the number of cross-validation folds (cv
), and the scoring metric (scoring
).
We then fit the grid search object to the training data using fit(X_train, y_train)
. After the grid search is complete, we output the best hyperparameters using grid_search.best_params_
.
Finally, we create a new XGBoost classifier with the best hyperparameters and fit it to the training data. We evaluate the model's accuracy on the test data using score(X_test, y_test)
.
This way, we can find the best combination of hyperparameters for the XGBoost model using grid search in Python.
gistlibby LogSnag