---
url: /dev/guides/scikit-learn.md
description: >-
  Use scikit-link models in scikit-learn pipelines, searches and
  meta-estimators, and fit scikit-learn transformers such as TF-IDF on the
  related tables.
---

# Use scikit-link with scikit-learn

**scikit-link estimators are scikit-learn estimators whose `X` is a table of
samples with an entity key; the related tables travel in the `database`
hyperparameter. Pipelines, searches and meta-estimators clone, slice and
wrap them as usual, and `RelationalFeaturizer` hands any scikit-learn model
a plain feature matrix.** This guide lists what works in each direction, the
few rules that keep the key column readable, and how to read the importances
of a scikit-learn model in terms of tables and columns.

## Setup

Install the [`pandas` extra](../getting-started/installation) for these
examples. The population `X` gets two sample features, an age with missing
values and a segment label, next to the key.

```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklink.datasets import make_relational_classification

db, X, y = make_relational_classification(
    600, signal="mixed", flip_y=0.05, output="pandas", random_state=0
)
rng = np.random.default_rng(0)
X = X.assign(
    age=np.where(np.arange(len(X)) % 7 == 0, np.nan, rng.normal(40, 10, len(X))),
    segment=rng.choice(["retail", "online", "store"], len(X)),
)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
```

## What works

With `database=None`, every relational estimator passes scikit-learn's
`check_estimator` suite, except for the checks that scikit-learn's own
forests and k-means also fail. The project's tests run the tools below.

| scikit-learn tool | With scikit-link |
|---|---|
| `clone`, `get_params`, `set_params`, `pickle`, joblib workers | The `Database` is shared, never copied: every clone, fold and worker reads the same object. |
| `Pipeline`, `make_pipeline`, `FeatureUnion`, `set_output` | `RelationalFeaturizer` outputs NumPy, pandas or Polars, with native categorical columns in data frames. |
| `ColumnTransformer` | In front of a relational model it encodes the sample features of `X` (see below); inside `TransformedTablesEstimator` it transforms the columns of a table. |
| `GridSearchCV`, `RandomizedSearchCV`, `HalvingGridSearchCV`, `cross_validate` | Parameters of nested steps tune as usual, and scikit-link's `TemporalCutoffSplit` works as the splitter. |
| `BaggingClassifier`, `AdaBoostClassifier`, `StackingClassifier`, `VotingClassifier`, `CalibratedClassifierCV`, `TunedThresholdClassifierCV`, `FixedThresholdClassifier`, `SelfTrainingClassifier`, `OneVsRestClassifier`, `MultiOutputClassifier`, `ClassifierChain`, `TransformedTargetRegressor`, `FrozenEstimator` | Fit and predict through the wrapper. Some of them pass `X` on as an array: give the key by position. |
| `permutation_importance`, `partial_dependence` | They permute or vary columns of `X`; the key column stands for all the related rows of a sample. |
| Metadata routing | `set_fit_request(sample_weight=True)` routes weights through `cross_validate`. |

## Name the key, or give its position

`key="customer_id"` finds the column by name, so `X` must have column names
when it reaches the estimator. Some meta-estimators, such as
`BaggingClassifier`, `SelfTrainingClassifier` and `ClassifierChain`, convert
`X` to a NumPy array first. Give the key by position for them, `key=0`, as in
the [bagging recipe](../cookbook/pipelines#bagging-and-other-meta-estimators-that-use-arrays).
A model fitted on a data frame also predicts on an array with the same
columns, and resolves the names by position.

## Encode the sample features of X

A `ColumnTransformer` in front of a relational model can impute, scale or
encode the columns of `X` other than the key. Two settings keep the key
readable for the model behind it. `set_output(transform="pandas")` keeps
column names, and `verbose_feature_names_out=False` keeps them unchanged:
by default the transformer renames the key to `remainder__customer_id`.

```python
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklink.tree import RelationalDecisionTreeClassifier

encode = ColumnTransformer(
    [
        ("age", SimpleImputer(), ["age"]),
        ("segment", OneHotEncoder(sparse_output=False), ["segment"]),
    ],
    remainder="passthrough",
    verbose_feature_names_out=False,
)
model = make_pipeline(
    encode,
    RelationalDecisionTreeClassifier(
        db, entity="customers", key="customer_id", max_depth=3, random_state=0
    ),
).set_output(transform="pandas")
model.fit(X_train, y_train)
print(f"{model.score(X_test, y_test):.3f}")
print(list(model[-1].feature_names_in_))
```

```text
0.933
['age', 'segment_online', 'segment_retail', 'segment_store', 'customer_id']
```

If a setting is missing, the error names it. Relational trees, forests and
boosting models read string and missing values of `X` themselves, so this
step is optional for them: add it when you want a specific imputation or
encoding.

## Hand relational features to any scikit-learn model

`RelationalFeaturizer` turns `X` into one row of aggregates per sample, so
any scikit-learn model can learn from the related tables. With pandas
output, categorical aggregates such as `mode(orders.type)` keep a categorical
dtype that `HistGradientBoostingClassifier` reads natively. The
[pipelines cookbook](../cookbook/pipelines) has recipes for linear models,
calibration, stacking and nearest neighbors.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklink.feature_extraction import RelationalFeaturizer

featurizer = RelationalFeaturizer(
    db, entity="customers", key="customer_id", max_relationship_depth=1
)
boosting = make_pipeline(
    featurizer,
    HistGradientBoostingClassifier(categorical_features="from_dtype", random_state=0),
).set_output(transform="pandas")
boosting.fit(X_train, y_train)
print(f"{boosting.score(X_test, y_test):.3f}")
```

```text
0.927
```

Inside a `ColumnTransformer`, give the featurizer the key column, and other
transformers the other columns. Its output names get the transformer's
prefix like any other.

## Transform the tables with scikit-learn

`TransformedTablesEstimator` fits scikit-learn transformers on the columns
of named tables, then fits the model on the transformed tables. Each
transformer learns only from the rows that the training samples reach, and
only from rows before their cutoffs in temporal mode, so the test samples
leak nothing into it; every row is then transformed. This is how a text
column, which relational models do not read, becomes usable. In this
example a customer's churn shows only in the words of their reviews.

```python
import pandas as pd
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import cross_val_score
from sklink import Database
from sklink.compose import TransformedTablesEstimator

n = 400
churned = rng.integers(0, 2, n)
author = rng.integers(0, n, 3 * n)
refund = rng.random(len(author)) < np.where(churned[author] == 1, 0.6, 0.1)
words = rng.choice(["delivery", "package", "size", "color", "price"], (len(author), 2))
reviews = pd.DataFrame(
    {
        "review_id": np.arange(len(author)),
        "customer_id": author,
        "stars": rng.integers(1, 6, len(author)),
        "comment": [
            f"{a} {b} {'refund' if r else 'thanks'}" for (a, b), r in zip(words, refund)
        ],
    }
)
shop = Database(
    {"customers": pd.DataFrame({"customer_id": np.arange(n)}), "reviews": reviews},
    primary_keys={"customers": "customer_id", "reviews": "review_id"},
    relationships=[("reviews.customer_id", "customers.customer_id")],
    column_types={"reviews": {"comment": "text"}},
)
customers = pd.DataFrame({"customer_id": np.arange(n)})

tree = RelationalDecisionTreeClassifier(
    shop, entity="customers", key="customer_id", max_depth=3, random_state=0
)
text = make_pipeline(TfidfVectorizer(), TruncatedSVD(2, random_state=0))
embed = ColumnTransformer(
    [("comment", text, "comment")],
    remainder="passthrough",
    verbose_feature_names_out=False,
)
model = TransformedTablesEstimator(tree, transformers=[("reviews", embed)])
print(f"{cross_val_score(tree, customers, churned, cv=5).mean():.3f}")
print(f"{cross_val_score(model, customers, churned, cv=5).mean():.3f}")
```

```text
0.532
0.787
```

The tree alone reads only the stars and the number of reviews, which say
nothing here. A transformer gives a table its new columns, `truncatedsvd0`
and `truncatedsvd1` here, and keeps the keys and the columns it passes
through. Its parameters tune in a search as `<table>__<parameter>`, such as
`reviews__comment__truncatedsvd__n_components`, and `aggregate_importances`
reads the fitted model by table. A model rebound to new tables with
`sklink.rebind` transforms them with what it learned in fit, as `transform`
does for `X`.

## Read the importances of a scikit-learn model by table

`aggregate_importances` groups importances by expression, table, column,
relationship or primitive. Behind a featurizer it reads the
`feature_importances_` of the last step, or the importances you pass, such
as the absolute coefficients of a linear model. Steps in between may impute,
scale or select columns, inside a `ColumnTransformer` or not: each column
the model receives is matched by name to the featurizer column it comes
from. The featurizer must be a step of the pipeline, not a transformer
inside a `ColumnTransformer`.

```python
from sklearn.ensemble import RandomForestClassifier
from sklink.inspection import aggregate_importances

forest = make_pipeline(
    RelationalFeaturizer(
        db, entity="customers", key="customer_id", max_relationship_depth=1
    ),
    SimpleImputer(),
    RandomForestClassifier(n_estimators=50, random_state=0),
).fit(X_train, y_train)
by_table = aggregate_importances(forest, by="table")
print({table: round(share, 3) for table, share in by_table.items()})
```

```text
{'orders': 0.87, 'customers': 0.12, 'X': 0.01}
```

One-hot encoding renames columns in a way that cannot be traced back, so
the function refuses it. For that case, or for importances measured on
held-out data, compute permutation importances of the rest of the pipeline
on the featurizer's output and pass them with the featurizer itself.
Permutation importances can be negative: `normalize=False` groups them
unchanged.

```python
from sklearn.inspection import permutation_importance

features = forest[0].transform(X_test)
result = permutation_importance(
    forest[1:], features, y_test, n_repeats=5, random_state=0
)
held_out = aggregate_importances(
    forest[0], by="table", importances=result.importances_mean, normalize=False
)
print({table: round(drop, 3) for table, drop in held_out.items()})
```

```text
{'orders': 0.381, 'customers': 0.128, 'X': 0.003}
```

`describe_expressions`, `ImportanceDisplay` and `SchemaDisplay` accept the
same pipelines.

## Limits

* The relational data is never part of `X`, `y` or the metadata that
  scikit-learn routes: a meta-estimator that needs it per sample cannot get it.
* Outputs are dense. A relational model returns one prediction per row of
  `X`, and the featurizer one row of features per row of `X`, in order.
* A transformer of `TransformedTablesEstimator` must return dense output
  with one row per row of its table: a sparse matrix, such as the default
  output of `OneHotEncoder` or of `TfidfVectorizer` alone, is refused.
  Reduce it to dense columns first, as `TruncatedSVD` does above.
