Blog

Find optimal parameters for CatBoost using GridSearchCV for Classification

image

Brief Description: Many a times while working on a dataset and using a Machine Learning model we don't know which set of Hyperparameters will give us the best result. Passing all sets of Hyperparameters manually through the model and checking the result might be a hectic work and may not be possible to do.

To get the best set of hyperparameters we can use Grid Search. Grid Search passes all combinations of hyperparameters one by one into the model and check the result. Finally, it gives us the set of hyperparemeters which gives the best result after passing in the model.

This python source code does the following:

1. pip installs Catboost
2. Imports SKlearn dataset
3. Performs validation dataset from the existing dataset
4. Applies Catboost Classifier
5. Hyperparameter tuning using GridSearchCV

Step 1 - Import the library – GridSearchCv

Here we have imported various modules like datasets, CatBoostClassifier and GridSearchCV from differnt libraries. We will understand the use of these later while using it in the in the code snipet.

For now just have a look on these imports.

So this recipe is a short example of how we can find optimal parameters using GridSearchCV.

Step 2 - Setup the Data

Here we have used datasets to load the inbuilt iris dataset and we have created objects X and y to store the data and the target value respectively.


Step 3 - Model and its Parameter

Here, we are using CatBoostClassifier as a Machine Learning model to use GridSearchCV. So we have created an object CBC.

Now we have defined the parameters of the model which we want to pass to through GridSearchCV to get the best parameters. So we are making an dictionary called parameters in which we have four parameters learning_rate, subsample, n_estimators and max_depth.


Step 4 - Using GridSearchCV and Printing Results

Before using GridSearchCV, lets have a look on the important parameters

  • estimator: In this we have to pass the models or functions on which we want to use GridSearchCV
  • param_grid: Dictionary or list of parameters of models or function in which GridSearchCV have to select the best.
  • Scoring: It is used as a evaluating metric for the model performance to decide the best hyperparameters, if not especified then it uses estimator score.
  • cv : In this we have to pass a interger value, as it signifies the number of splits that is needed for cross validation. By default is set as five.
  • n_jobs : This signifies the number of jobs to be run in parallel, -1 signifies to use all processor.
Making an object grid_GBC for GridSearchCV and fitting the dataset i.e X and y

Now we are using print statements to print the results. It will give the values of hyperparameters as a result.

** For output, please run above codes on your python