---
url: /stable/api/sklink.compose.md
description: >-
  API reference of sklink.compose. Combine relational estimators with
  scikit-learn transformers of tables.
---

::: v-pre

# `sklink.compose` {#sklink.compose}

Combine relational estimators with scikit-learn transformers of tables.

* `TransformedTablesEstimator` fits scikit-learn transformers on tables
  of the database, with the rows the training samples reach, before a
  relational estimator reads them.

**Classes:**

* [**TransformedTablesEstimator**](#sklink.compose.TransformedTablesEstimator): Fit scikit-learn transformers on tables of the database, then an estimator.

## `sklink.compose.TransformedTablesEstimator` {#sklink.compose.TransformedTablesEstimator}

```python
TransformedTablesEstimator(estimator: Any = None, *, transformers: Sequence[tuple[str, Any]] = ()) -> None
```

Bases: [MetaEstimatorMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.MetaEstimatorMixin.html), VersionedStateMixin, [BaseEstimator](https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html)

Fit scikit-learn transformers on tables of the database, then an estimator.

Each transformer replaces the columns of one table of the `database` of
`estimator`, for example to embed a text column with TF-IDF and truncated
SVD, scale amounts or bin a numeric column, before `estimator` reads the
table. In `fit`, a transformer learns only from the rows of its table that
the training samples can reach through the relationships: the same rows
that the relational estimators read for them, at any depth, and in
temporal mode only the rows visible at their cutoffs. It then transforms
the whole table, so that `predict` and `transform` read the rows of
new samples with what was learned in `fit`. Inside a cross-validation,
each fold learns its own statistics, as with a transformer of `X` in a
[`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html).

The transformer of a table receives the columns of the table that are
not keys, not the time column, not `id` columns and not excluded from
features, in the order of the table: a pandas `DataFrame`, a Polars one
if pandas is not installed, and a NumPy array without either, whose
columns a [`ColumnTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html) then selects by
position. The keys, the time column, the `id` and the excluded columns
are kept unchanged; the transformer's output columns replace all the
others, so a [`ColumnTransformer`](https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html) with
`remainder="passthrough"` keeps the columns it does not transform. Pass
`verbose_feature_names_out=False` to keep their names: expressions are
named after the columns, as in `mean(orders.amount)`. An output that is
an array takes its column names from `get_feature_names_out`, given the
input column names. Output columns are typed like the columns of a new
[`Database`](./sklink#sklink.Database), and keep the `column_types` declared for a
column of the same name. The output must be dense, with one row per row
of the table, and must not reuse the name of a kept column.

**Guides:** [Transform the tables with scikit-learn](../guides/scikit-learn#transform-the-tables-with-scikit-learn)

**Parameters:**

* **estimator** ([estimator](#sklink.compose.TransformedTablesEstimator.estimator)): A relational estimator, a [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) or a
  meta-estimator that holds one or several of them. Every `database`
  parameter inside it is the same [`Database`](./sklink#sklink.Database), which the
  transformed database replaces. The rows reachable from the samples
  are found with the entity, key and time of the relational estimator
  that receives `X`: `estimator` itself, the first step of a
  pipeline, or the estimator a meta-estimator wraps.
* **transformers** (list of (str, transformer) tuples): Table name and unfitted scikit-learn transformer. Parameters of a
  transformer are set and tuned as `<table>__<parameter>`, those of
  the estimator as `estimator__<parameter>`. With no transformers, or
  without a database (flat mode), the estimator is fitted unchanged.

**Attributes:**

* **estimator\_** ([estimator](#sklink.compose.TransformedTablesEstimator.estimator)): The fitted estimator, which reads the transformed database.
* **transformers\_** (dict of str to transformer): The fitted transformer of each table.
* **schema\_** ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the schema of the original database that the fitted model
  needs: the transformed tables in full and what the estimator reads
  of the others. [`sklink.rebind`](./sklink#sklink.rebind) checks a new database against it.
* [**classes\_**](#sklink.compose.TransformedTablesEstimator.classes_) (ndarray): Labels of a classifier.
* [**n\_features_in\_**](#sklink.compose.TransformedTablesEstimator.n_features_in_) ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* [**feature_names_in\_**](#sklink.compose.TransformedTablesEstimator.feature_names_in_) (ndarray of str): Column names of `X`, when it has them.

sklearn.compose.TransformedTargetRegressor : Transform the target.

The relational configuration of the wrapped model reads through: the
attributes `database`, `entity`, `key` and `time` are those of the
relational estimator that receives `X`, and `set_params` accepts
`database` (set on every parameter inside the estimator that holds a
database, or on that of the estimator that receives `X` if none does),
`entity`, `key`, `time`, `allow_reverse_paths` and
`handle_unknown_entity` for it. They are not parameters of this
class, so `get_params` and [`clone`](https://scikit-learn.org/stable/modules/generated/sklearn.base.clone.html) do not list
them.

Fitting builds a new database with the transformed tables, in which only
the output columns of the transformers take new memory: the other tables
and the kept columns share their data with the original database. After
[`sklink.rebind`](./sklink#sklink.rebind) to another database, the first call to `predict`
or `transform` transforms its tables with the fitted transformers,
without fitting them again, and the model keeps the result for the next
calls. Each transformer receives the columns it
was fitted on, in the same order, even if the new table has more columns
or orders them differently. A copy, a pickled and loaded model, or
`set_output` transforms the tables again on first use.

**Examples:**

The transformer of `orders` receives its columns other than keys,
`type` and `amount`; position 1, which also works without pandas,
selects `amount`.

```pycon
>>> from sklearn.compose import ColumnTransformer
>>> from sklearn.preprocessing import KBinsDiscretizer
>>> from sklink.compose import TransformedTablesEstimator
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> discretize = KBinsDiscretizer(3, encode="ordinal", strategy="uniform")
>>> bins = ColumnTransformer(
...     [("amount", discretize, [1])],
...     remainder="passthrough",
...     verbose_feature_names_out=False,
... )
>>> model = TransformedTablesEstimator(
...     RelationalDecisionTreeClassifier(
...         shop.database, entity="customers", key=0, max_depth=2
...     ),
...     transformers=[("orders", bins)],
... ).fit(shop.X, shop.y)
>>> model.predict(shop.X[:3]).shape
(3,)
```

**Functions:**

* [**decision_function**](#sklink.compose.TransformedTablesEstimator.decision_function): Decision function of the estimator on the transformed database.
* [**fit**](#sklink.compose.TransformedTablesEstimator.fit): Fit the transformers on the reachable rows, then the estimator.
* [**fit_predict**](#sklink.compose.TransformedTablesEstimator.fit_predict): Fit the transformers, then the estimator with its `fit_predict`.
* [**fit_transform**](#sklink.compose.TransformedTablesEstimator.fit_transform): Fit the transformers, then the estimator with its `fit_transform`.
* [**get_feature_names_out**](#sklink.compose.TransformedTablesEstimator.get_feature_names_out): Output names of the estimator, such as a featurizer.
* [**get_metadata_routing**](#sklink.compose.TransformedTablesEstimator.get_metadata_routing): Route metadata such as `sample_weight` to the estimator.
* [**get_params**](#sklink.compose.TransformedTablesEstimator.get_params): Get the parameters, with those of the estimator and the transformers.
* [**predict**](#sklink.compose.TransformedTablesEstimator.predict): Predict with the estimator on the transformed database.
* [**predict_log_proba**](#sklink.compose.TransformedTablesEstimator.predict_log_proba): Log of the class probabilities of the estimator.
* [**predict_proba**](#sklink.compose.TransformedTablesEstimator.predict_proba): Class probabilities of the estimator on the transformed database.
* [**score**](#sklink.compose.TransformedTablesEstimator.score): Score of the estimator on the transformed database.
* [**score_samples**](#sklink.compose.TransformedTablesEstimator.score_samples): Sample scores of the estimator, such as an anomaly score.
* [**set_output**](#sklink.compose.TransformedTablesEstimator.set_output): Set the output container of the estimator's `transform`.
* [**set_params**](#sklink.compose.TransformedTablesEstimator.set_params): Set parameters, including a whole transformer as `<table>`.
* [**transform**](#sklink.compose.TransformedTablesEstimator.transform): Transform with the estimator, such as a featurizer, on the new tables.

### `sklink.compose.TransformedTablesEstimator.classes_` {#sklink.compose.TransformedTablesEstimator.classes\_}

```python
classes_: Any
```

Labels of the fitted classifier.

### `sklink.compose.TransformedTablesEstimator.database` {#sklink.compose.TransformedTablesEstimator.database}

```python
database: Any
```

The database inside the estimator, or `None` in flat mode.

### `sklink.compose.TransformedTablesEstimator.decision_function` {#sklink.compose.TransformedTablesEstimator.decision_function}

```python
decision_function(X: Any) -> Any
```

Decision function of the estimator on the transformed database.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.

**Returns:**

* **scores** (ndarray): The estimator's decision function.

### `sklink.compose.TransformedTablesEstimator.entity` {#sklink.compose.TransformedTablesEstimator.entity}

```python
entity: Any
```

`entity` of the relational estimator that receives `X`.

### `sklink.compose.TransformedTablesEstimator.estimator` {#sklink.compose.TransformedTablesEstimator.estimator}

```python
estimator = estimator
```

### `sklink.compose.TransformedTablesEstimator.feature_names_in_` {#sklink.compose.TransformedTablesEstimator.feature_names_in\_}

```python
feature_names_in_: Any
```

Column names of `X` seen in `fit`, when it had them.

### `sklink.compose.TransformedTablesEstimator.fit` {#sklink.compose.TransformedTablesEstimator.fit}

```python
fit(X: Any, y: Any = None, **fit_params: Any) -> Self
```

Fit the transformers on the reachable rows, then the estimator.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table, as the estimator expects it.
* **y** (array-like of shape (n_samples,)): Target, passed to the estimator.
* \*\***fit_params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `fit`, or routed to it when metadata
  routing is enabled.

**Returns:**

* **self** ([TransformedTablesEstimator](#sklink.compose.TransformedTablesEstimator)): Fitted estimator.

### `sklink.compose.TransformedTablesEstimator.fit_predict` {#sklink.compose.TransformedTablesEstimator.fit_predict}

```python
fit_predict(X: Any, y: Any = None, **fit_params: Any) -> Any
```

Fit the transformers, then the estimator with its `fit_predict`.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* **y** (array-like of shape (n_samples,)): Target, passed to the estimator.
* \*\***fit_params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `fit_predict`, or routed to it when
  metadata routing is enabled.

**Returns:**

* **labels** (ndarray of shape (n_samples,)): The estimator's labels of `X`, such as clusters.

### `sklink.compose.TransformedTablesEstimator.fit_transform` {#sklink.compose.TransformedTablesEstimator.fit_transform}

```python
fit_transform(X: Any, y: Any = None, **fit_params: Any) -> Any
```

Fit the transformers, then the estimator with its `fit_transform`.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* **y** (array-like of shape (n_samples,)): Target, passed to the estimator.
* \*\***fit_params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `fit_transform`, or routed to it when
  metadata routing is enabled.

**Returns:**

* **X\_out** (ndarray or DataFrame): The estimator's output for `X`.

### `sklink.compose.TransformedTablesEstimator.get_feature_names_out` {#sklink.compose.TransformedTablesEstimator.get_feature_names_out}

```python
get_feature_names_out(input_features: Any = None) -> Any
```

Output names of the estimator, such as a featurizer.

**Parameters:**

* **input_features** (array-like of str): Passed to the estimator.

**Returns:**

* **names** (ndarray of str): The estimator's output names.

### `sklink.compose.TransformedTablesEstimator.get_metadata_routing` {#sklink.compose.TransformedTablesEstimator.get_metadata_routing}

```python
get_metadata_routing() -> MetadataRouter
```

Route metadata such as `sample_weight` to the estimator.

**Returns:**

* **routing** ([MetadataRouter](https://scikit-learn.org/stable/modules/generated/sklearn.utils.metadata_routing.MetadataRouter.html)): Routing of `fit`, `predict`, `score` and the other methods
  that take metadata to the same method of `estimator`.
  Transformers of tables receive no metadata.

### `sklink.compose.TransformedTablesEstimator.get_params` {#sklink.compose.TransformedTablesEstimator.get_params}

```python
get_params(deep: bool = True) -> dict[str, Any]
```

Get the parameters, with those of the estimator and the transformers.

**Parameters:**

* **deep** ([bool](https://docs.python.org/3/library/functions.html#bool)): Also return `estimator__<name>`, `<table>` and
  `<table>__<name>` for the estimator and each transformer.

**Returns:**

* **params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Parameter names mapped to their values.

### `sklink.compose.TransformedTablesEstimator.key` {#sklink.compose.TransformedTablesEstimator.key}

```python
key: Any
```

`key` of the relational estimator that receives `X`.

### `sklink.compose.TransformedTablesEstimator.n_features_in_` {#sklink.compose.TransformedTablesEstimator.n_features_in\_}

```python
n_features_in_: int
```

Number of columns of `X` seen in `fit`.

### `sklink.compose.TransformedTablesEstimator.predict` {#sklink.compose.TransformedTablesEstimator.predict}

```python
predict(X: Any, **params: Any) -> Any
```

Predict with the estimator on the transformed database.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `predict`, or routed to it when
  metadata routing is enabled.

**Returns:**

* **y\_pred** (ndarray of shape (n_samples,)): The estimator's predictions.

### `sklink.compose.TransformedTablesEstimator.predict_log_proba` {#sklink.compose.TransformedTablesEstimator.predict_log_proba}

```python
predict_log_proba(X: Any) -> Any
```

Log of the class probabilities of the estimator.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.

**Returns:**

* **log_proba** (ndarray of shape (n_samples, n_classes)): The estimator's log-probabilities.

### `sklink.compose.TransformedTablesEstimator.predict_proba` {#sklink.compose.TransformedTablesEstimator.predict_proba}

```python
predict_proba(X: Any, **params: Any) -> Any
```

Class probabilities of the estimator on the transformed database.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `predict_proba`, or routed to it when
  metadata routing is enabled.

**Returns:**

* **proba** (ndarray of shape (n_samples, n_classes)): The estimator's probabilities, columns in the order of `classes_`.

### `sklink.compose.TransformedTablesEstimator.score` {#sklink.compose.TransformedTablesEstimator.score}

```python
score(X: Any, y: Any = None, **params: Any) -> float
```

Score of the estimator on the transformed database.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* **y** (array-like of shape (n_samples,)): True values.
* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `score`, such as `sample_weight`,
  or routed to it when metadata routing is enabled.

**Returns:**

* **score** ([float](https://docs.python.org/3/library/functions.html#float)): The estimator's score.

### `sklink.compose.TransformedTablesEstimator.score_samples` {#sklink.compose.TransformedTablesEstimator.score_samples}

```python
score_samples(X: Any) -> Any
```

Sample scores of the estimator, such as an anomaly score.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.

**Returns:**

* **scores** (ndarray of shape (n_samples,)): The estimator's scores.

### `sklink.compose.TransformedTablesEstimator.set_output` {#sklink.compose.TransformedTablesEstimator.set_output}

```python
set_output(*, transform: str | None = None) -> Self
```

Set the output container of the estimator's `transform`.

**Parameters:**

* **transform** ((default, pandas, polars)): Passed to the estimator's `set_output`.

**Returns:**

* **self** ([TransformedTablesEstimator](#sklink.compose.TransformedTablesEstimator)): The estimator.

### `sklink.compose.TransformedTablesEstimator.set_params` {#sklink.compose.TransformedTablesEstimator.set_params}

```python
set_params(**params: Any) -> Self
```

Set parameters, including a whole transformer as `<table>`.

**Parameters:**

* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Parameter names, as `get_params` returns them, and values.

**Returns:**

* **self** ([TransformedTablesEstimator](#sklink.compose.TransformedTablesEstimator)): The estimator.

### `sklink.compose.TransformedTablesEstimator.time` {#sklink.compose.TransformedTablesEstimator.time}

```python
time: Any
```

`time` of the relational estimator that receives `X`.

### `sklink.compose.TransformedTablesEstimator.transform` {#sklink.compose.TransformedTablesEstimator.transform}

```python
transform(X: Any, **params: Any) -> Any
```

Transform with the estimator, such as a featurizer, on the new tables.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table.
* \*\***params** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Passed to the estimator's `transform`, or routed to it when
  metadata routing is enabled.

**Returns:**

* **X\_out** (ndarray or DataFrame): The estimator's output.

### `sklink.compose.TransformedTablesEstimator.transformers` {#sklink.compose.TransformedTablesEstimator.transformers}

```python
transformers = transformers
```

:::
