---
url: /dev/api/sklink.feature_extraction.md
description: >-
  API reference of sklink.feature_extraction. Turn relational data into flat
  feature matrices for any estimator.
---

::: v-pre

# `sklink.feature_extraction` {#sklink.feature_extraction}

Turn relational data into flat feature matrices for any estimator.

**Classes:**

* [**RelationalFeaturizer**](#sklink.feature_extraction.RelationalFeaturizer): Turn a population table into a flat matrix of relational features.

## `sklink.feature_extraction.RelationalFeaturizer` {#sklink.feature_extraction.RelationalFeaturizer}

```python
RelationalFeaturizer(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', conditional: bool = True, max_categories: int = 10, max_features: int | None = None, windows: Sequence[str | dt.timedelta | np.timedelta64] | None = None, include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, allow_reverse_paths: bool = False, passthrough: bool = True, handle_unknown_entity: Literal['error', 'empty'] = 'error', feature_names: Literal['canonical', 'safe'] = 'canonical', n_jobs: int | None = None) -> None
```

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

Turn a population table into a flat matrix of relational features.

Each output column is an expression evaluated on the database for every
row of `X`, such as `mean(orders.amount)` or
`count(orders[type == 'express'])`. The catalog of expressions depends on
the schema and the hyperparameters, and on the data only through category
vocabularies learned in `fit` from rows reachable from the training
samples. Use it in a [`Pipeline`](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) in front of any
tabular estimator.

Time is optional: without `time` every related row is used; with
`time`, rows of tables with a time column are used only if they happened
before the sample's cutoff.

**Guides:** [Relational features](../tutorials/relational-features), [Use with scikit-learn](../guides/scikit-learn)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database) or None): Relational data. `None` makes the transformer return `X` unchanged
  (flat mode).
* **entity** ([str](https://docs.python.org/3/library/stdtypes.html#str)): Table of `database` the samples belong to.
* **key** (([str](https://docs.python.org/3/library/stdtypes.html#str), [int](https://docs.python.org/3/library/functions.html#int) or sequence)): Column(s) of `X` with the entity key, by name or position. `None`
  uses the columns named like the entity's primary key.
* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample. `None` is static mode.
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationships followed from the entity table.
* **max_lookup_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of lookups (many-to-one steps after the last table of a path)
  from the rows of a path to the columns that its category conditions read,
  such as `count(orders.order_items[products.category == 'toys'])`, and that
  are aggregated like the columns of the path's last table, such as
  `mean(orders.order_items.products.price)`. These lookups reach one row per
  row and do not count towards `max_relationship_depth`. They continue only
  the paths of exactly `max_relationship_depth` hops, since shorter paths
  already reach those tables, and never reach the entity table unless
  `allow_reverse_paths=True`. `0` keeps conditions on the last table of
  the path.
* **primitives** ("default" or list of str): Aggregations to apply. `"default"` picks them from each column's type;
  in temporal mode, numeric columns of tables with a time column also get
  `last` (the latest non-missing value among the rows visible at the
  cutoff) and `trend` (the least-squares slope of the value over time,
  per day).
* **conditional** ([bool](https://docs.python.org/3/library/functions.html#bool)): Also aggregate the numeric columns of a table with `mean` and `sum`
  (those of them that a list of `primitives` names) over the rows of
  each category of its categorical columns and of the columns its rows
  look up (see `max_lookup_depth`), such as
  `sum(orders.amount[type == 'express'])`. Only columns with at most
  `max_categories` categories among the rows reachable from the
  training samples get them, so that high-cardinality columns do not
  multiply the catalog. Pass `False` for a smaller catalog on wide
  tables.
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#int)): Number of most frequent categories per categorical column that get their
  own `count` and `proportion` features.
* **max_features** ([int](https://docs.python.org/3/library/functions.html#int)): Raise an error if the catalog has more expressions than this.
* **windows** (list of str, timedelta or timedelta64): Temporal mode only: also aggregate over these windows before the cutoff.
  Strings use the duration grammar of
  [`TemporalCutoffSplit`](./sklink.model_selection#sklink.model_selection.TemporalCutoffSplit): an integer and a
  unit (`W`, `D`, `h`, `min`, `s`, `ms`, `us`, `ns`),
  possibly combined, such as `"30D"` or `"1D12h"`.
* **include** (list of str): Glob patterns over canonical names, table names or relationship names.
* **exclude** (list of str): Glob patterns over canonical names, table names or relationship names.
* **allow_reverse_paths** ([bool](https://docs.python.org/3/library/functions.html#bool)): Allow paths that read rows of other entities through shared tables.
* **passthrough** ([bool](https://docs.python.org/3/library/functions.html#bool)): Keep the columns of `X` other than `key` and `time` as features.
* **handle_unknown_entity** ((error, empty)): What to do with keys of `X` missing from the entity table.
* **feature_names** ((canonical, safe)): Output names: canonical expression names, or short stable aliases.
* **n\_jobs** ([int](https://docs.python.org/3/library/functions.html#int)): Reserved for parallel evaluation; results never depend on it.

**Attributes:**

* **expressions\_** (tuple of Expression): Expression of every output column.
* **categories\_** (dict of str to ndarray): Vocabulary of every categorical output column.
* **categorical_features\_** (ndarray of bool): Mask of categorical output columns (integer codes).
* [**schema\_**](#sklink.feature_extraction.RelationalFeaturizer.schema_) ([Schema](./sklink.database#sklink.database.Schema)): Part of the schema the transformer reads.
* **visibility\_** ([Visibility](./sklink.engine#sklink.engine.Visibility)): Visibility policy used in `fit`.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of str): Column names of `X`, when it has them.
* **n\_features_out\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of output columns.

sklink.tree.RelationalDecisionTreeClassifier : A tree that learns its
questions about the related tables, conditions included, while it
grows.
sklink.tree.RelationalDecisionTreeRegressor : The same tree for a numeric
target.
sklink.inspection.describe_expressions : What each output column reads.

**Examples:**

```pycon
>>> import numpy as np
>>> from sklink import Database
>>> from sklink.feature_extraction import RelationalFeaturizer
>>> db = Database(
...     {
...         "customers": {"customer_id": np.array([1, 2])},
...         "orders": {
...             "order_id": np.array([10, 11, 12]),
...             "customer_id": np.array([1, 1, 2]),
...             "amount": np.array([5.0, 7.0, 3.0]),
...         },
...     },
...     primary_keys={"customers": "customer_id", "orders": "order_id"},
...     relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> feat = RelationalFeaturizer(db, entity="customers", key=0)
>>> X = np.array([[1], [2], [1]])
>>> feat.fit_transform(X)[:, :3]
array([[2., 1., 7.],
       [1., 1., 3.],
       [2., 1., 7.]])
>>> list(feat.get_feature_names_out()[:3])
['count(orders)', 'exists(orders)', 'max(orders.amount)']
```

**Functions:**

* [**fit**](#sklink.feature_extraction.RelationalFeaturizer.fit): Learn the catalog of expressions and the category vocabularies.
* [**get_feature_names_out**](#sklink.feature_extraction.RelationalFeaturizer.get_feature_names_out): Names of the output columns.
* [**set_output**](#sklink.feature_extraction.RelationalFeaturizer.set_output): Set the output container of `transform` and `fit_transform`.
* [**transform**](#sklink.feature_extraction.RelationalFeaturizer.transform): Evaluate the learned expressions for every row of `X`.

### `sklink.feature_extraction.RelationalFeaturizer.allow_reverse_paths` {#sklink.feature_extraction.RelationalFeaturizer.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.feature_extraction.RelationalFeaturizer.conditional` {#sklink.feature_extraction.RelationalFeaturizer.conditional}

```python
conditional = conditional
```

### `sklink.feature_extraction.RelationalFeaturizer.database` {#sklink.feature_extraction.RelationalFeaturizer.database}

```python
database = database
```

### `sklink.feature_extraction.RelationalFeaturizer.entity` {#sklink.feature_extraction.RelationalFeaturizer.entity}

```python
entity = entity
```

### `sklink.feature_extraction.RelationalFeaturizer.exclude` {#sklink.feature_extraction.RelationalFeaturizer.exclude}

```python
exclude = exclude
```

### `sklink.feature_extraction.RelationalFeaturizer.expressions` {#sklink.feature_extraction.RelationalFeaturizer.expressions}

```python
expressions: tuple[Expression, ...]
```

Alias of `expressions_` for introspection tools.

### `sklink.feature_extraction.RelationalFeaturizer.feature_names` {#sklink.feature_extraction.RelationalFeaturizer.feature_names}

```python
feature_names = feature_names
```

### `sklink.feature_extraction.RelationalFeaturizer.fit` {#sklink.feature_extraction.RelationalFeaturizer.fit}

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

Learn the catalog of expressions and the category vocabularies.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features.
* **y** (None): Ignored.

**Returns:**

* **self** ([RelationalFeaturizer](#sklink.feature_extraction.RelationalFeaturizer)): Fitted transformer.

### `sklink.feature_extraction.RelationalFeaturizer.get_feature_names_out` {#sklink.feature_extraction.RelationalFeaturizer.get_feature_names_out}

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

Names of the output columns.

**Parameters:**

* **input_features** (array-like of str): Names of the columns of `X`. If `X` had column names in `fit`,
  they must be equal to `feature_names_in_`. Otherwise they name the
  passed-through columns instead of `x0`, `x1`, ... (safe aliases
  always derive from the canonical names).

**Returns:**

* **names** (ndarray of str): Canonical expression names, or `f{n}_{hash}` aliases with
  `feature_names="safe"`.

**Raises:**

* [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError): If `input_features` does not have one name per column of `X`,
  or differs from `feature_names_in_`.

### `sklink.feature_extraction.RelationalFeaturizer.handle_unknown_entity` {#sklink.feature_extraction.RelationalFeaturizer.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.feature_extraction.RelationalFeaturizer.include` {#sklink.feature_extraction.RelationalFeaturizer.include}

```python
include = include
```

### `sklink.feature_extraction.RelationalFeaturizer.key` {#sklink.feature_extraction.RelationalFeaturizer.key}

```python
key = key
```

### `sklink.feature_extraction.RelationalFeaturizer.max_categories` {#sklink.feature_extraction.RelationalFeaturizer.max_categories}

```python
max_categories = max_categories
```

### `sklink.feature_extraction.RelationalFeaturizer.max_features` {#sklink.feature_extraction.RelationalFeaturizer.max_features}

```python
max_features = max_features
```

### `sklink.feature_extraction.RelationalFeaturizer.max_lookup_depth` {#sklink.feature_extraction.RelationalFeaturizer.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.feature_extraction.RelationalFeaturizer.max_relationship_depth` {#sklink.feature_extraction.RelationalFeaturizer.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.feature_extraction.RelationalFeaturizer.n_jobs` {#sklink.feature_extraction.RelationalFeaturizer.n_jobs}

```python
n_jobs = n_jobs
```

### `sklink.feature_extraction.RelationalFeaturizer.passthrough` {#sklink.feature_extraction.RelationalFeaturizer.passthrough}

```python
passthrough = passthrough
```

### `sklink.feature_extraction.RelationalFeaturizer.primitives` {#sklink.feature_extraction.RelationalFeaturizer.primitives}

```python
primitives = primitives
```

### `sklink.feature_extraction.RelationalFeaturizer.schema_` {#sklink.feature_extraction.RelationalFeaturizer.schema\_}

```python
schema_: Schema | None
```

### `sklink.feature_extraction.RelationalFeaturizer.set_output` {#sklink.feature_extraction.RelationalFeaturizer.set_output}

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

Set the output container of `transform` and `fit_transform`.

**Parameters:**

* **transform** ((default, pandas, polars)): `"pandas"` and `"polars"` give a DataFrame with native
  categorical and nullable boolean columns; `"default"` gives the
  `float64` array; `None` leaves the configuration unchanged.

**Returns:**

* **self** ([RelationalFeaturizer](#sklink.feature_extraction.RelationalFeaturizer)): The transformer.

### `sklink.feature_extraction.RelationalFeaturizer.time` {#sklink.feature_extraction.RelationalFeaturizer.time}

```python
time = time
```

### `sklink.feature_extraction.RelationalFeaturizer.transform` {#sklink.feature_extraction.RelationalFeaturizer.transform}

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

Evaluate the learned expressions for every row of `X`.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **X\_out** (ndarray or DataFrame of shape (n_samples, n_features_out\_)): By default, features as `float64` with `NaN` for missing
  values; categorical columns hold codes into `categories_`. With
  `set_output(transform="pandas")` or `"polars"`, a DataFrame
  whose categorical columns have a native categorical dtype with the
  labels of `categories_` and whose boolean columns are nullable
  booleans. Polars categoricals hold strings, so non-string labels
  are written with [`str`](https://docs.python.org/3/library/stdtypes.html#str) there.

### `sklink.feature_extraction.RelationalFeaturizer.windows` {#sklink.feature_extraction.RelationalFeaturizer.windows}

```python
windows = windows
```

:::
