---
url: /dev/tutorials/model-selection.md
description: >-
  Tune relational models with GridSearchCV and cross_validate, choose a
  splitter, and use pipelines and scikit-learn meta-estimators with scikit-link.
---

# Model selection and hyperparameter search

**Use scikit-learn's model-selection tools with the population table `X` and
its labels `y`. Pass the `Database` to the estimator when you construct it,
then choose a splitter that matches how you will predict.** Each fold fits
its own estimator on its training samples.

## What each fold sees {#why-it-is-safe}

`clone` leaves the new estimator pointing to the same immutable `Database`.
The fitted state belongs to each fold. When `fit` learns category
vocabularies, bins or split conditions, it uses the related rows reachable
from that fold's training samples.

```python
from sklearn.base import clone
from sklink.datasets import make_relational_classification
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=800, signal="mixed", random_state=1
)
tree = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", random_state=0
)
print(clone(tree).database is db)
```

```text
True
```

## Tune a pipeline

Keep the featurizer inside the pipeline so each fold learns its feature
catalog from its own training rows. Name the steps and use `step__parameter`
in the grid. This search tries two settings for category-specific aggregates
and two learning rates for the classifier.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklink.feature_extraction import RelationalFeaturizer

pipe = Pipeline(
    [
        (
            "features",
            RelationalFeaturizer(
                db, entity="customers", key="customer_id", max_relationship_depth=1
            ),
        ),
        ("model", HistGradientBoostingClassifier(random_state=0)),
    ]
)
search = GridSearchCV(
    pipe,
    {"features__conditional": [False, True], "model__learning_rate": [0.05, 0.1]},
    cv=StratifiedKFold(5, shuffle=True, random_state=0),
    scoring="roc_auc",
)
search.fit(X, y)
print(search.best_params_)
print(f"ROC AUC {search.best_score_:.3f}")
```

```text
{'features__conditional': True, 'model__learning_rate': 0.1}
ROC AUC 0.989
```

`best_params_` gives the combination with the highest mean cross-validation
ROC AUC.

## Tune a relational tree

This grid varies tree depth, the number of conditions a split can learn on
related rows, and the minimum number of training samples in a leaf.

```python
search = GridSearchCV(
    tree,
    {"max_depth": [2, 4, 6], "max_conditions": [1, 2], "min_samples_leaf": [1, 10]},
    cv=5,
    scoring="roc_auc",
)
search.fit(X, y)
print(search.best_params_)
print(f"ROC AUC {search.best_score_:.3f}")
```

```text
{'max_conditions': 2, 'max_depth': 4, 'min_samples_leaf': 10}
ROC AUC 0.971
```

`best_params_` gives the depth, number of conditions and leaf size of the
best tree in this grid. For a forest, you can also search over
`max_features` to vary the number of candidate groups each node considers.

## Several metrics at once

Pass a list to `scoring` to report several metrics on the same folds.

```python
from sklearn.model_selection import cross_validate

scores = cross_validate(
    search.best_estimator_, X, y, cv=5, scoring=["accuracy", "roc_auc"]
)
for name in ["test_accuracy", "test_roc_auc"]:
    print(f"{name}: {scores[name].mean():.3f}")
```

```text
test_accuracy: 0.932
test_roc_auc: 0.971
```

These folds also selected the tree's settings. To estimate performance after
tuning, score the selected model on a separate holdout, or run the search
inside each training fold of an outer cross-validation.

## Choosing the splitter

| Your data | Splitter |
| --- | --- |
| One row per entity, no time | `KFold` for regression or `StratifiedKFold` for classification |
| Several rows per entity, predicting for unseen entities | `GroupKFold(n_splits)` with `groups=X["customer_id"]` |
| Predicting for later cutoffs | `TemporalCutoffSplit`, see [Time and cutoffs](./time-and-cutoffs) |

For unseen customers, grouping keeps every row for one customer on the same
side of a split. To measure future predictions, split by cutoff so the
training samples come from earlier times. `TemporalCutoffSplit` ignores
`groups`: to test unseen customers at later cutoffs, hold out a set of
customers first, then split the remaining samples by cutoff.

## Meta-estimators

Relational estimators also work inside `BaggingClassifier`,
`CalibratedClassifierCV`, `StackingClassifier` and `VotingClassifier`. Some
meta-estimators pass an array in place of a DataFrame. Pass `key=0` (and `time=1` in
temporal mode) when your wrapper drops column names. See the examples in
[Pipelines and meta-estimators](../cookbook/pipelines).

After selecting a model, [inspect what it learned](./inspect-and-explain).
