---
url: /blog/scikit-learn-multiple-tables.md
description: >-
  Step-by-step Python tutorial: train a scikit-learn model on customers and
  orders, from groupby and merge to relational features and trees, without
  leakage.
---

# How to train a scikit-learn model on multiple tables

**A tabular scikit-learn estimator expects one feature row per sample.** You
can build those rows with `groupby` and `merge` or with a relational featurizer
inside a scikit-learn `Pipeline`. A relational tree can search the related
rows during `fit` and use what it finds in its splits.

To run the examples, install scikit-link with pandas. Run the
Python blocks in order in the same session.

```bash
pip install "scikit-link[pandas]"
```

## The problem: customers and their orders

We want to predict which customers will upgrade to a premium plan. Each
customer has one row in `customers` and can have several rows in `orders`.
The `customer_id` column links the two tables.

```python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
n_customers = 1000
customers = pd.DataFrame(
    {
        "customer_id": np.arange(n_customers),
        "country": rng.choice(["CO", "PE", "MX", "CL"], n_customers),
    }
)
n_orders = 9000
orders = pd.DataFrame(
    {
        "order_id": np.arange(n_orders),
        "customer_id": rng.integers(0, n_customers, n_orders),
        "type": rng.choice(
            ["express", "standard", "pickup"], n_orders, p=[0.15, 0.6, 0.25]
        ),
        "amount": rng.gamma(2.0, 40.0, n_orders).round(2),
    }
)
# Customers upgrade when they place at least one large express order.
large_express = orders[(orders["type"] == "express") & (orders["amount"] > 100)]
y = customers["customer_id"].isin(large_express["customer_id"]).astype(int).to_numpy()
print(customers.shape, orders.shape, f"positive rate {y.mean():.2f}")
```

```text
(1000, 2) (9000, 4) positive rate 0.32
```

These labels come from a rule built into the example. The scores show which
features recover that rule on this dataset.

## The usual way: groupby, merge, then fit

Aggregate the orders per customer, merge the result into the customer table,
and fit a model.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score

features = orders.groupby("customer_id").agg(
    n_orders=("order_id", "count"),
    mean_amount=("amount", "mean"),
    max_amount=("amount", "max"),
    n_express=("type", lambda t: (t == "express").sum()),
)
flat = customers.merge(features, on="customer_id", how="left").fillna(
    {"n_orders": 0, "n_express": 0}
)
X_flat = flat[["n_orders", "mean_amount", "max_amount", "n_express"]]
score = cross_val_score(
    HistGradientBoostingClassifier(random_state=0), X_flat, y, cv=5, scoring="roc_auc"
).mean()
print(f"hand-written features, ROC AUC: {score:.3f}")
```

```text
hand-written features, ROC AUC: 0.797
```

The maximum order amount could come from a standard order. The number of
express orders gives no information about their amounts. To record the joint
condition by hand, add a feature such as the maximum express order amount.

## The scikit-link way: describe the tables once

Describe the source tables, primary keys and relationships in a `Database`.
The database is a parameter of the estimator. `X` has one row per customer
and carries the key used to find their related rows.

```python
from sklink import Database

db = Database(
    tables={"customers": customers, "orders": orders},
    primary_keys={"customers": "customer_id", "orders": "order_id"},
    relationships=[("orders.customer_id", "customers.customer_id")],
)
X = customers[["customer_id"]]
```

## Relational features in a pipeline

`RelationalFeaturizer` uses the schema to choose which aggregates to compute.
By default it also computes means and sums within frequent categories, such
as `mean(orders.amount[type == 'express'])`. Gradient boosting can then split
on that feature.

```python
from sklearn.pipeline import make_pipeline
from sklink.feature_extraction import RelationalFeaturizer

pipe = make_pipeline(
    RelationalFeaturizer(db, entity="customers", key="customer_id"),
    HistGradientBoostingClassifier(random_state=0),
)
print(
    f"relational features, ROC AUC: {cross_val_score(pipe, X, y, cv=5, scoring='roc_auc').mean():.3f}"
)
```

```text
relational features, ROC AUC: 0.988
```

The featurizer is refitted on each training fold, so category vocabularies
never come from the test fold.

## A tree that learns the condition

A relational decision tree does not need the feature to exist in advance. It
searches the category, the threshold and the aggregate while it grows.

```python
from sklink.inspection import export_text
from sklink.tree import RelationalDecisionTreeClassifier

tree = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    max_depth=2,
    random_state=0,
)
print(
    f"relational tree, ROC AUC: {cross_val_score(tree, X, y, cv=5, scoring='roc_auc').mean():.3f}"
)
print(export_text(tree.fit(X, y)))
```

```text
relational tree, ROC AUC: 0.999
|--- exists(orders[amount > 99.97 & type == 'express']) <= 0.500
|   |--- class: 0
|--- exists(orders[amount > 99.97 & type == 'express']) >  0.500
|   |--- class: 1
```

The fitted split recovers the rule up to a learned amount threshold near 100.
The score comes from cross-validation. The printed tree was fitted separately
on all the data so you can inspect it.

## What changes in practice

| | Hand-written `groupby` | scikit-link |
| --- | --- | --- |
| Features | Aggregates specified in code | A catalog from the schema, or searched by the tree |
| Conditions such as `amount > 100 & type == 'express'` | Specified in code | A relational tree searches both predicates during `fit` |
| Cross-validation | Fit any data-dependent preprocessing inside each fold | Pipeline refits the featurizer inside each fold |
| Names | Column names supplied by the author | Canonical names, such as `count(orders[...])` |
| Works with `Pipeline`, `GridSearchCV` | After flattening | Directly, `X` has one row per sample |

## Build on the example {#try-it}

The [quickstart](https://scikit-link.rodrigo-arenas.com/stable/getting-started/quickstart)
uses a shop dataset. To go further, fit a
[relational random forest](https://scikit-link.rodrigo-arenas.com/stable/tutorials/relational-random-forests)
or [gradient boosting](https://scikit-link.rodrigo-arenas.com/stable/tutorials/relational-gradient-boosting).
For model selection and deployment, see the
[tutorials](https://scikit-link.rodrigo-arenas.com/stable/tutorials/).
Questions about your own schema are welcome in
[GitHub Discussions](https://github.com/rodrigo-arenas/scikit-link/discussions).
