---
url: /stable/api/sklink.datasets.md
description: >-
  API reference of sklink.datasets. Synthetic relational datasets and a small
  bundled example database.
---

::: v-pre

# `sklink.datasets` {#sklink.datasets}

Synthetic relational datasets and a small bundled example database.

The `make_*` generators return a triple `(database, X, y)`: unlike
`sklearn.datasets`, the relational data cannot travel inside `X`.

**Functions:**

* [**load_shop**](#sklink.datasets.load_shop): Load the small shop database bundled with the package.
* [**make_relational_classification**](#sklink.datasets.make_relational_classification): Generate a relational classification problem with a known rule.
* [**make_relational_regression**](#sklink.datasets.make_relational_regression): Generate a relational regression problem with a known target formula.

## `sklink.datasets.load_shop` {#sklink.datasets.load_shop}

```python
load_shop(*, output: Output = 'auto') -> Bunch
```

Load the small shop database bundled with the package.

A static database of invented data (no dates, a few dozen rows per table)
with customers, their orders, the order items and the products. It loads
without network access and without pandas. See `DESCR` in the result for
the full description.

**Guides:** [Quickstart](../getting-started/quickstart)

**Parameters:**

* **output** (('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and of `X`. `"auto"` is `"pandas"` when
  pandas is installed and `"numpy"` otherwise. With `"numpy"` each
  table is a `dict` of 1-D arrays and `X` a 2-D array.

**Returns:**

* **data** ([`Bunch`](https://scikit-learn.org/stable/modules/generated/sklearn.utils.Bunch.html)): Dictionary-like object with the following attributes.

database : Database
The tables `customers`, `orders`, `order_items` and
`products`.
X : DataFrame or ndarray of shape (24, 1)
Population table: one row per customer with `customer_id`.
y : ndarray of shape (24,)
1 for a loyal customer (at least 3 orders), 0 otherwise.
entity : str
The entity table, `"customers"`.
key : str
The key column of `X`, `"customer_id"`.
time : None
The database has no time column.
DESCR : str
Description of the dataset.

**Raises:**

* [ImportError](https://docs.python.org/3/library/exceptions.html#ImportError): If `output` names a library that is not installed.

sklink.datasets.make_relational_classification : Synthetic classification
problems of any size, with a known rule.
sklink.datasets.make_relational_regression : Synthetic regression problems
of any size, with a known target formula.

**Examples:**

```pycon
>>> from sklink.datasets import load_shop
>>> shop = load_shop()
>>> shop.database.table_names
('customers', 'orders', 'order_items', 'products')
>>> shop.database.n_rows("orders")
56
>>> shop.X.shape, shop.y.shape
((24, 1), (24,))
```

## `sklink.datasets.make_relational_classification` {#sklink.datasets.make_relational_classification}

```python
make_relational_classification(n_entities: int = 1000, *, n_child_rows: int | tuple[int, int] = (0, 20), signal: Signal = 'child_categorical', n_classes: int = 2, n_informative_root: int | None = None, n_noise_root: int = 2, n_noise_child: int = 3, n_noise_tables: int = 0, flip_y: float = 0.0, class_sep: float = 1.0, with_time: bool = False, n_cutoffs: int = 1, missing_rate: float = 0.0, orphan_rate: float = 0.0, return_rule: bool = False, output: Output = 'auto', random_state: int | np.random.RandomState | None = None) -> tuple[Database, Any, NDArray[np.int64]] | tuple[Database, Any, NDArray[np.int64], str]
```

Generate a relational classification problem with a known rule.

Unlike [`sklearn.datasets.make_classification`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html), this returns a
**triple** `(database, X, y)`: the relational data cannot travel in `X`.
`X` is the population table with one row per sample, holding the entity
key `customer_id` and, only with `with_time=True`, the `cutoff` column.

The database always has the same tables:

* `customers(customer_id, x_root_*, noise_root_*)`, the entity table.
* `orders(order_id, customer_id, type, amount, noise_child_*)`, children
  of `customers`. `type` is categorical (`'express'`,
  `'standard'`, `'pickup'`, `'economy'`) and `amount` numeric.
  With `with_time=True` it also has the time column `created_at`.
* `order_items(item_id, order_id, product_id, quantity)`, children of
  `orders`.
* `products(product_id, category, price)`, parents of `order_items`.
* `noise_0`, `noise_1`, ...: `n_noise_tables` children of
  `customers` (`noise_<i>_id, customer_id, value_num, value_cat`)
  without signal.

Identifiers are `int64`. No table has a date column unless
`with_time=True`.

**Guides:** [Case study: scikit-learn toolbox](../case-studies/scikit-learn-toolbox)

**Parameters:**

* **n\_entities** ([int](https://docs.python.org/3/library/functions.html#int)): Number of customers.

* **n\_child_rows** (int or tuple of (int, int)): Orders per customer: a fixed number, or an inclusive `(min, max)`
  range drawn uniformly. With `min=0` some customers have no orders.

* **signal** ([str](https://docs.python.org/3/library/stdtypes.html#str)): What the label depends on. The label is a deterministic function of
  the aggregate below (before `flip_y`):

* `"root"`: a linear combination of the `x_root_*` columns.

* `"child_numeric"`: `mean(orders.amount)`.

* `"child_categorical"`: `proportion(orders[type == 'express'])`.

* `"conditional"`:
  `count(orders[amount > t & type == 'express']) >= k`. The number
  of express orders and the number of orders above `t` have the same
  distribution in both classes; only their conjunction is informative.

* `"multihop"`: the proportion of order items whose product has
  `category == 'toys'`, reached through `orders` and
  `order_items`.

* `"mixed"`: majority vote of three rules, on the root columns, on
  `proportion(orders[type == 'pickup'])` and the conditional rule.

Thresholds are chosen from the generated data so that classes are
balanced. A customer whose aggregate is undefined (no rows) is in
class 0.

* **n\_classes** ([int](https://docs.python.org/3/library/functions.html#int)): Number of classes, formed by quantile thresholds of the aggregate.
  `"conditional"` and `"mixed"` support only 2.
* **n\_informative_root** ([int](https://docs.python.org/3/library/functions.html#int) or None): Number of `x_root_*` columns the root rule uses. `None` means 2
  for `"root"` and `"mixed"` and 0 otherwise. It must be positive
  for those signals and 0 for the others.
* **n\_noise_root** ([int](https://docs.python.org/3/library/functions.html#int)): Number of `noise_root_*` columns of `customers`, without signal.
* **n\_noise_child** ([int](https://docs.python.org/3/library/functions.html#int)): Number of `noise_child_*` columns of `orders`, without signal.
  Even indices are numeric and odd indices categorical.
* **n\_noise_tables** ([int](https://docs.python.org/3/library/functions.html#int)): Number of extra child tables of `customers` without signal.
* **flip\_y** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of labels replaced by a random class after applying the rule.
* **class_sep** ([float](https://docs.python.org/3/library/functions.html#float)): How far apart the classes are generated. Larger values move the
  aggregates of each class away from the rule's thresholds. With
  `flip_y=0` the rule separates the classes exactly for any value.
* **with_time** ([bool](https://docs.python.org/3/library/functions.html#bool)): Add the time column `orders.created_at` and the `cutoff` column of
  `X`. The label is then the rule evaluated on the orders created
  before the cutoff, and each cutoff is followed by orders that follow
  the pattern of the opposite class: a model that ignores the cutoff
  learns from the future and fails on data available at prediction time.
* **n\_cutoffs** ([int](https://docs.python.org/3/library/functions.html#int)): Number of cutoffs, 90 days apart. `X` holds one row per customer
  and cutoff, sorted by cutoff. Values above 1 need `with_time=True`.
* **missing_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of missing values in each of `orders.type`,
  `orders.amount`, `orders.noise_child_*` and the value columns of the
  noise tables. A comparison with a missing value is false.
* **orphan_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of rows of `orders` and of the noise tables whose
  `customer_id` does not exist in `customers`. The database is then
  built with `orphans="ignore"`.
* **return_rule** ([bool](https://docs.python.org/3/library/functions.html#bool)): Also return the generating rule as a string (see Notes).
* **output** (('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and of `X`. `"auto"` is `"pandas"` when
  pandas is installed and `"numpy"` otherwise. With `"numpy"` each
  table is a `dict` of 1-D arrays and `X` a 2-D array (`object`
  dtype when it mixes types).
* **random_state** (int, RandomState instance or None): Seed for the generation. Pass an int for reproducible output.

**Returns:**

* **database** ([Database](./sklink#sklink.Database)): The relational data.
* **X** (DataFrame or ndarray of shape (n_samples, 1 or 2)): Population table: `customer_id` and, with `with_time=True`,
  `cutoff`. `n_samples = n_entities * n_cutoffs`.
* **y** (ndarray of shape (n_samples,)): Integer class labels.
* **rule** ([str](https://docs.python.org/3/library/stdtypes.html#str)): The generating rule. Only returned with `return_rule=True`.

**Raises:**

* [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError): If `signal` is unknown, if `n_cutoffs > 1` without
  `with_time=True` or if a parameter is out of range.
* [ImportError](https://docs.python.org/3/library/exceptions.html#ImportError): If `output` names a library that is not installed.

sklink.datasets.make_relational_regression : The same tables with a
numeric target.
sklink.datasets.load_shop : A small, fixed example database.

The rule is written as an aggregate followed by its threshold, such as
`count(orders[amount > 100.0 & type == 'express']) >= 3`:

* Aggregates are `count`, `proportion`, `mean` and `sum` over a
  path of table names joined by `.` starting at the entity, such as
  `orders` or `orders.order_items.products`. A column follows the
  path, as in `mean(orders.amount)`.
* Conditions go inside `[...]`, joined by `&`, sorted by column name
  and then operator. `proportion(path[cond])` is the number of rows that
  meet the condition divided by the number of rows.
* Numbers are written with [`repr`](https://docs.python.org/3/library/functions.html#repr), so `float(text)` round-trips.
  Strings are single-quoted; a backslash or a single quote inside them is
  preceded by a backslash.
* The root rule is a linear combination such as
  `1.2 * x_root_0 - 0.7 * x_root_1 >= 0.05`.
* With more than two classes the rule is `digitize(<aggregate>, [t1, t2])`:
  the class is the number of thresholds the aggregate reaches.
* `"mixed"` is `(<rule>) + (<rule>) + (<rule>) >= 2`.

With `with_time=True` the thresholds are chosen at the first cutoff and
kept for the others.

**Examples:**

```pycon
>>> from sklink.datasets import make_relational_classification
>>> database, X, y, rule = make_relational_classification(
...     n_entities=200, signal="conditional", return_rule=True, random_state=0
... )
>>> database.table_names
('customers', 'orders', 'order_items', 'products')
>>> X.shape, y.shape
((200, 1), (200,))
>>> rule
"count(orders[amount > 100.0 & type == 'express']) >= 1"
```

## `sklink.datasets.make_relational_regression` {#sklink.datasets.make_relational_regression}

```python
make_relational_regression(n_entities: int = 1000, *, n_child_rows: int | tuple[int, int] = (0, 20), signal: Signal = 'child_categorical', n_informative_root: int | None = None, n_noise_root: int = 2, n_noise_child: int = 3, n_noise_tables: int = 0, noise: float = 0.0, with_time: bool = False, n_cutoffs: int = 1, missing_rate: float = 0.0, orphan_rate: float = 0.0, return_rule: bool = False, output: Output = 'auto', random_state: int | np.random.RandomState | None = None) -> tuple[Database, Any, NDArray[np.float64]] | tuple[Database, Any, NDArray[np.float64], str]
```

Generate a relational regression problem with a known target formula.

Returns a **triple** `(database, X, y)` with the same tables and
population as `make_relational_classification`.

**Parameters:**

* **n\_entities** ([int](https://docs.python.org/3/library/functions.html#int)): Number of customers.

* **n\_child_rows** (int or tuple of (int, int)): Orders per customer: a fixed number, or an inclusive `(min, max)`
  range drawn uniformly.

* **signal** ([str](https://docs.python.org/3/library/stdtypes.html#str)): What the target is, before `noise`. Every aggregate is defined for
  customers without rows:

* `"root"`: a linear combination of the `x_root_*` columns.

* `"child_numeric"`: `sum(orders.amount)`.

* `"child_categorical"`: `count(orders[type == 'express'])`.

* `"conditional"`: `count(orders[amount > t & type == 'express'])`.

* `"multihop"`:
  `count(orders.order_items.products[category == 'toys'])`.

* `"mixed"`: the root combination plus
  `count(orders[type == 'pickup'])` plus the conditional count.

* **n\_informative_root** ([int](https://docs.python.org/3/library/functions.html#int) or None): Number of `x_root_*` columns the root formula uses. `None` means 2
  for `"root"` and `"mixed"` and 0 otherwise.

* **n\_noise_root** ([int](https://docs.python.org/3/library/functions.html#int)): Number of `noise_root_*` columns of `customers`.

* **n\_noise_child** ([int](https://docs.python.org/3/library/functions.html#int)): Number of `noise_child_*` columns of `orders`.

* **n\_noise_tables** ([int](https://docs.python.org/3/library/functions.html#int)): Number of extra child tables of `customers` without signal.

* **noise** ([float](https://docs.python.org/3/library/functions.html#float)): Standard deviation of the Gaussian noise added to the target.

* **with_time** ([bool](https://docs.python.org/3/library/functions.html#bool)): Add `orders.created_at` and the `cutoff` column of `X`; the
  target uses only the orders created before the cutoff. See
  `make_relational_classification`.

* **n\_cutoffs** ([int](https://docs.python.org/3/library/functions.html#int)): Number of cutoffs. Values above 1 need `with_time=True`.

* **missing_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of missing values in the non-key columns of `orders` and of
  the noise tables.

* **orphan_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of rows of `orders` and of the noise tables whose
  `customer_id` does not exist in `customers`.

* **return_rule** ([bool](https://docs.python.org/3/library/functions.html#bool)): Also return the target formula as a string, in the format described in
  `make_relational_classification`, without a threshold.

* **output** (('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and of `X`.

* **random_state** (int, RandomState instance or None): Seed for the generation. Pass an int for reproducible output.

**Returns:**

* **database** ([Database](./sklink#sklink.Database)): The relational data.
* **X** (DataFrame or ndarray of shape (n_samples, 1 or 2)): Population table: `customer_id` and, with `with_time=True`,
  `cutoff`.
* **y** (ndarray of shape (n_samples,)): Float target.
* **rule** ([str](https://docs.python.org/3/library/stdtypes.html#str)): The target formula. Only returned with `return_rule=True`.

**Raises:**

* [ValueError](https://docs.python.org/3/library/exceptions.html#ValueError): If `signal` is unknown, if `n_cutoffs > 1` without
  `with_time=True` or if a parameter is out of range.
* [ImportError](https://docs.python.org/3/library/exceptions.html#ImportError): If `output` names a library that is not installed.

sklink.datasets.make_relational_classification : The same tables with
class labels.
sklink.datasets.load_shop : A small, fixed example database.

**Examples:**

```pycon
>>> from sklink.datasets import make_relational_regression
>>> database, X, y, rule = make_relational_regression(
...     n_entities=100, signal="multihop", return_rule=True, random_state=0
... )
>>> rule
"count(orders.order_items.products[category == 'toys'])"
>>> y.dtype
dtype('float64')
```

:::
