To fit an XGBoost regressor with grid search over parameters in Python, you can use the GridSearchCV class from the sklearn library. Here's an example of how you can do it:
First, import the necessary libraries:
main.py71 chars3 lines
Next, define the XGBoost regressor and the parameter grid:
main.py159 chars8 lines
Then, create the GridSearchCV object and fit it to your data:
main.py149 chars3 lines
In the code above, X_train
and y_train
are your input features and target variables, respectively. The cv
parameter specifies the number of cross-validation folds, and scoring
indicates the evaluation metric you want to use.
Finally, you can access the best estimator and its parameters:
main.py84 chars3 lines
The best_estimator
variable holds the trained XGBoost regressor with the best combination of parameters found during grid search, and best_params
contains the best parameters selected by the grid search.
Note: Make sure you have the xgboost library installed in your Python environment before running this code. You can install it using pip install xgboost
.
I hope this helps! Let me know if you have any further questions.
gistlibby LogSnag