---
url: /dev/cookbook/evaluation.md
description: >-
  Recipes to evaluate relational models: cross-validation, grouped and temporal
  splits, hyperparameter search and fair comparisons with flattened features.
---

# Evaluation and tuning

**Compare a model trained on the entity table with one that also uses related
rows. Score both on the same folds before tuning their parameters.** Use a
split that matches how you will use the model. The [model selection tutorial](../tutorials/model-selection)
walks through that choice.

## Setup

Run this block first. It creates a static dataset with one sample per customer
and a label that depends on both customer details and order history. Install
the [`pandas` extra](../getting-started/installation) to run these examples.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklink.datasets import make_relational_classification
from sklink.feature_extraction import RelationalFeaturizer
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=800, signal="mixed", output="pandas", random_state=0
)
```

## How much do the related tables add?

Fit the same classifier with two sets of inputs. First, `exclude=["orders"]`
keeps only the features from the customer table. Then let the featurizer use
orders as well, including aggregates such as the mean amount for express
orders. `max_relationship_depth=1` limits the walk to one relationship from
`customers`, so it stops at `orders`.

```python
def score(**params):
    pipe = make_pipeline(
        RelationalFeaturizer(
            db,
            entity="customers",
            key="customer_id",
            max_relationship_depth=1,
            **params,
        ).set_output(transform="pandas"),
        HistGradientBoostingClassifier(random_state=0),
    )
    return cross_val_score(pipe, X, y, cv=5, scoring="roc_auc").mean()


print(f"entity table only {score(exclude=['orders']):.3f}")
print(f"with orders       {score():.3f}")
```

```text
entity table only 0.755
with orders       0.990
```

The score rises when the model can read orders in this synthetic example.
Both runs use the same five folds and ROC AUC, which measures how well the
model ranks positive samples above negative samples. The featurizer is fitted
inside the pipeline on each training fold.

## Keep a customer's rows together {#several-rows-per-entity}

Use `GroupKFold` if you want to predict for customers the model has never
seen. Give it the customer IDs as `groups`, so each customer's rows stay on
one side of the split. This example gives each customer three snapshots.
The tree sees only orders before a snapshot's cutoff. Grouping keeps
customers apart across folds, while the cutoff controls which orders a sample
can read. For predicting at later dates, use
[`TemporalCutoffSplit`](../tutorials/time-and-cutoffs#temporal-cross-validation)
to keep training cutoffs earlier than test cutoffs.

```python
from sklearn.model_selection import GroupKFold

db_t, X_t, y_t = make_relational_classification(
    n_entities=300, with_time=True, n_cutoffs=3, output="pandas", random_state=0
)
tree = RelationalDecisionTreeClassifier(
    db_t,
    entity="customers",
    key="customer_id",
    time="cutoff",
    max_depth=3,
    max_relationship_depth=1,
    random_state=0,
)
scores = cross_val_score(tree, X_t, y_t, cv=GroupKFold(5), groups=X_t["customer_id"])
print(f"{scores.mean():.3f}")
```

```text
0.999
```

## Randomized search over a relational forest

`RandomizedSearchCV` tries four combinations of parameters and scores each on
three folds. `max_features` controls how many candidate features each split
considers. `max_conditions` limits how many filters an aggregate can combine,
and `min_samples_leaf` sets the smallest allowed leaf.

```python
from scipy.stats import randint
from sklearn.model_selection import RandomizedSearchCV
from sklink.ensemble import RelationalRandomForestClassifier

forest = RelationalRandomForestClassifier(
    db,
    entity="customers",
    key="customer_id",
    n_estimators=30,
    n_jobs=1,
    random_state=0,
)
search = RandomizedSearchCV(
    forest,
    {
        "max_features": [0.3, 0.5, None],
        "max_conditions": [1, 2],
        "min_samples_leaf": randint(1, 20),
    },
    n_iter=4,
    cv=3,
    scoring="roc_auc",
    random_state=0,
)
search.fit(X, y)
print(search.best_params_)
print(f"{search.best_score_:.3f}")
```

```text
{'max_conditions': 2, 'max_features': 0.5, 'min_samples_leaf': 19}
0.973
```

`best_score_` comes from the folds used to choose the settings. To estimate
performance after tuning, score `best_estimator_` on a separate test set or
evaluate the search itself with nested cross-validation.

## Featurizer or relational tree?

Compare both on the same folds. A featurizer builds a feature matrix for
gradient boosting. A relational tree learns a single set of decision rules
you can inspect. Here the boosting pipeline scores higher. Use the same
comparison on your own data to see how much the scores differ.

```python
folds = StratifiedKFold(5, shuffle=True, random_state=0)
candidates = {
    "featurizer + boosting": make_pipeline(
        RelationalFeaturizer(
            db,
            entity="customers",
            key="customer_id",
            max_relationship_depth=1,
        ).set_output(transform="pandas"),
        HistGradientBoostingClassifier(random_state=0),
    ),
    "relational tree": RelationalDecisionTreeClassifier(
        db,
        entity="customers",
        key="customer_id",
        max_depth=4,
        min_samples_leaf=10,
        random_state=0,
    ),
}
for name, model in candidates.items():
    print(
        f"{name:22} {cross_val_score(model, X, y, cv=folds, scoring='roc_auc').mean():.3f}"
    )
```

```text
featurizer + boosting  0.990
relational tree        0.964
```
