---
metadata:
  - name: generator
    content: Diplodoc Platform v5.50.3
alternate:
  - https://catboost.ai/docs/en/concepts/python-reference_catboostregressor_grid_search.md
---
> **Documentation Index:** Fetch the complete configuration index at https://catboost.ai/docs/en/llms.txt

# grid_search

<!-- source: en/_includes/work_src/reusage-python/grid-search__div__desc.md -->
A simple grid search over specified parameter values for a model.

<!-- source: en/_includes/work_src/reusage-python/python__grid_search__note.md -->
{% note info %}

After searching, the model is trained and ready to use.

{% endnote %}
<!-- endsource: en/_includes/work_src/reusage-python/python__grid_search__note.md -->
<!-- endsource: en/_includes/work_src/reusage-python/grid-search__div__desc.md -->


## Method call format {#method-call-format}

```python
grid_search(param_grid,
            X,
            y=None,
            cv=3,
            partition_random_seed=0,
            calc_cv_statistics=True,
            search_by_train_test_split=True,
            refit=True,
            shuffle=True,
            stratified=None,
            train_size=0.8,
            verbose=True,
            plot=False,
            log_cout=sys.stdout,
            log_cerr=sys.stderr)
```

## Parameters {#parameters}

### param_grid

#### Description

Dictionary with parameters names (string) as keys and lists of parameter settings to try as values, or a list of such dictionaries, in which case the grids spanned by each dictionary in the list are explored.

This enables searching over any sequence of parameter settings.


**Possible types**


- dict
- list

**Default value**

Required parameter

### X

#### Description

The description is different for each group of possible types.

**Possible types**

{% cut "catboost.Pool" %}

The input training dataset.

{% note info %}

If a nontrivial value of the `cat_features` parameter is specified in the constructor of this class, CatBoost checks the equivalence of categorical features indices specification from the constructor parameters and in this Pool class.

{% endnote %}

{% endcut %}


{% cut "numpy.ndarray, pandas.DataFrame, polars.DataFrame" %}

The input training dataset in the form of a two-dimensional feature matrix.

{% endcut %}


{% cut "pandas.SparseDataFrame, scipy.sparse.spmatrix (all subclasses except dia_matrix)" %}

<!-- source: en/_includes/work_src/reusage-formats/libsvm__desc.md -->
The input training dataset in the form of a two-dimensional sparse feature matrix.
<!-- endsource: en/_includes/work_src/reusage-formats/libsvm__desc.md -->

{% endcut %}

**Possible types**


<!-- source: en/_includes/work_src/reusage-formats/libsvm__desc.md -->
The input training dataset in the form of a two-dimensional sparse feature matrix.
<!-- endsource: en/_includes/work_src/reusage-formats/libsvm__desc.md -->


**Default value**

Required parameter

### y

#### Description

<!-- source: en/_includes/work_src/reusage/label--short-desc-training.md -->
The target variables (in other words, the objects' label values) for the training dataset.
<!-- endsource: en/_includes/work_src/reusage/label--short-desc-training.md -->

<!-- source: en/_includes/work_src/reusage/label--detailed-desc-regression.md -->
Must be in the form of a one- or two- dimensional array. The type of data in the array depends on the machine learning task being solved:
- Regression — One-dimensional array of numeric values.
- Multiregression - Two-dimensional array of numeric values. The first index is for a dimension, the second index is for an object.
<!-- endsource: en/_includes/work_src/reusage/label--detailed-desc-regression.md -->

{% note info %}

Do not use this parameter if the input training dataset (specified in the `X` parameter) type is catboost.Pool.

{% endnote %}

<!-- source: en/_includes/work_src/reusage/label--possible-types-default-supported-processing-units.md -->
**Possible types**

- list
- numpy.ndarray
- pandas.DataFrame
- pandas.Series
- [polars.Series](https://docs.pola.rs/api/python/stable/reference/series/index.html)
- [polars.DataFrame](https://docs.pola.rs/api/python/stable/reference/dataframe/index.html)

**Default value**

None

**Supported processing units**

CPU and GPU
<!-- endsource: en/_includes/work_src/reusage/label--possible-types-default-supported-processing-units.md -->

### cv

#### Description


The cross-validation splitting strategy.

The interpretation of this parameter depends on the input data type:
- None —  Use the default three-fold cross-validation.
- int —  The number of folds in a (Stratified)KFold
- <!-- source: en/_includes/work_src/reusage-python/object-scikitlearn.md -->
  object — One of the scikit-learn Splitter Classes with the `split` method.
  <!-- endsource: en/_includes/work_src/reusage-python/object-scikitlearn.md -->

- An iterable yielding train and test splits as arrays of indices.


**Possible types**


- int
- scikit-learn splitter object
- cross-validation generator
- iterable

**Default value**

None

### partition_random_seed

#### Description


<!-- source: en/_includes/work_src/reusage/cv-rand__desc_intro.md -->
Use this as the seed value for random permutation of the data.
<!-- endsource: en/_includes/work_src/reusage/cv-rand__desc_intro.md -->


<!-- source: en/_includes/work_src/reusage/cv-rand__permutation-is-performed.md -->
The permutation is performed before splitting the data for cross-validation.
<!-- endsource: en/_includes/work_src/reusage/cv-rand__permutation-is-performed.md -->


<!-- source: en/_includes/work_src/reusage/cv-rand__unique-data-splits.md -->
Each seed generates unique data splits.
<!-- endsource: en/_includes/work_src/reusage/cv-rand__unique-data-splits.md -->


**Possible types**

int

**Default value**

`0`

### calc_cv_statistics

#### Description

Estimate the quality by using cross-validation with the best of the found parameters. The model is fitted using these parameters.

This option can be enabled if the `search_by_train_test_split` parameter is set to True.

**Possible types**

bool

**Default value**

True

### search_by_train_test_split

#### Description

Split the source dataset into train and test parts. Models are trained on the train part, while parameters are compared by the loss function score on the test dataset.

It is recommended to enable this option for large datasets and disable it for the small ones.


**Possible types**

bool

**Default value**

True

### refit

#### Description

Refit an estimator using the best-found parameters on the whole dataset.

**Possible types**

bool

**Default value**

`True`

### shuffle

#### Description

Shuffle the dataset objects before splitting into folds.

**Possible types**

bool

**Default value**

`True`

### stratified

#### Description

Perform stratified sampling. True for classification and False otherwise.

**Possible types**

bool

**Default value**

None

### train_size

#### Description

The proportion of the dataset to include in the train split.

Possible values are in the range [0;1].

**Possible types**

float

**Default value**

0.8

### verbose

#### Description

<!-- source: en/_includes/work_src/reusage/python__feature-importances__verbose__short-description__list-intro.md -->
The purpose of this parameter depends on the type of the given value:
<!-- endsource: en/_includes/work_src/reusage/python__feature-importances__verbose__short-description__list-intro.md -->


- int —  The frequency of iterations to print the information to stdout.
- bool —  Print the information to stdout on every iteration (if set to <q>True</q>) or disable any logging (if set to <q>False</q>).

**Possible types**


- bool
- int

**Default value**

True

### plot

#### Description

Draw train and evaluation metrics for every set of parameters in Jupyter [Jupyter Notebook](https://catboost.ai/docs/en/features/visualization_jupyter-notebook.md).

**Possible types**

bool

**Default value**

False

<!-- source: en/_includes/work_src/reusage-python/python__log-params.md -->
###  log_cout

Output stream or callback for logging.

**Possible types**

- callable Python object
- python object providing the `write()` method

**Default value**

sys.stdout

###  log_cerr

Error stream or callback for logging.

**Possible types**

- callable Python object
- python object providing the `write()` method

**Default value**

sys.stderr
<!-- endsource: en/_includes/work_src/reusage-python/python__log-params.md -->

## Return value {#output-format}

Dict with two fields:

- `params` — `dict` of best-found parameters.
- `cv_results` — `dict` or pandas.core.frame.DataFrame with cross-validation results. Сolumns are: `test-error-mean`, `test-error-std`, `train-error-mean`, `train-error-std`.

## Examples {#example}

```python
from catboost import CatBoostRegressor
import numpy as np

train_data = np.random.randint(1, 100, size=(100, 10))
train_labels = np.random.randint(2, size=(100))

model = CatBoostRegressor()

grid = {'learning_rate': [0.03, 0.1],
        'depth': [4, 6, 10],
        'l2_leaf_reg': [1, 3, 5, 7, 9]}

grid_search_result = model.grid_search(grid,
                                       X=train_data,
                                       y=train_labels,
                                       plot=True)

```

<!-- source: en/_includes/work_src/reusage-code-examples/graph-plotted-with-jupyter-notebook.md -->
The following is a chart plotted with [Jupyter Notebook](https://catboost.ai/docs/en/features/visualization_jupyter-notebook.md) for the given example.
<!-- endsource: en/_includes/work_src/reusage-code-examples/graph-plotted-with-jupyter-notebook.md -->

![](../images/interface__catboostregressor__grid_search.png)
