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: Load the small shop database bundled with the package.
- make_relational_classification: Generate a relational classification problem with a known rule.
- make_relational_regression: Generate a relational regression problem with a known target formula.
sklink.datasets.load_shop
load_shop(*, output: Output = 'auto') -> BunchLoad 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
Parameters:
- output (
('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and ofX."auto"is"pandas"when pandas is installed and"numpy"otherwise. With"numpy"each table is adictof 1-D arrays andXa 2-D array.
Returns:
- data (
): Dictionary-like object with the following attributes.Bunch
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: Ifoutputnames a library that is not installed.
See Also
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:
>>> 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
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, 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 ofcustomers.typeis categorical ('express','standard','pickup','economy') andamountnumeric. Withwith_time=Trueit also has the time columncreated_at.order_items(item_id, order_id, product_id, quantity), children oforders.products(product_id, category, price), parents oforder_items.noise_0,noise_1, ...:n_noise_tableschildren ofcustomers(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
Parameters:
n_entities (
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. Withmin=0some customers have no orders.signal (
str): What the label depends on. The label is a deterministic function of the aggregate below (beforeflip_y):"root": a linear combination of thex_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 abovethave the same distribution in both classes; only their conjunction is informative."multihop": the proportion of order items whose product hascategory == 'toys', reached throughordersandorder_items."mixed": majority vote of three rules, on the root columns, onproportion(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): Number of classes, formed by quantile thresholds of the aggregate."conditional"and"mixed"support only 2. - n_informative_root (
int or None): Number ofx_root_*columns the root rule uses.Nonemeans 2 for"root"and"mixed"and 0 otherwise. It must be positive for those signals and 0 for the others. - n_noise_root (
int): Number ofnoise_root_*columns ofcustomers, without signal. - n_noise_child (
int): Number ofnoise_child_*columns oforders, without signal. Even indices are numeric and odd indices categorical. - n_noise_tables (
int): Number of extra child tables ofcustomerswithout signal. - flip_y (
float): Fraction of labels replaced by a random class after applying the rule. - class_sep (
float): How far apart the classes are generated. Larger values move the aggregates of each class away from the rule's thresholds. Withflip_y=0the rule separates the classes exactly for any value. - with_time (
bool): Add the time columnorders.created_atand thecutoffcolumn ofX. 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): Number of cutoffs, 90 days apart.Xholds one row per customer and cutoff, sorted by cutoff. Values above 1 needwith_time=True. - missing_rate (
float): Fraction of missing values in each oforders.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): Fraction of rows ofordersand of the noise tables whosecustomer_iddoes not exist incustomers. The database is then built withorphans="ignore". - return_rule (
bool): Also return the generating rule as a string (see Notes). - output (
('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and ofX."auto"is"pandas"when pandas is installed and"numpy"otherwise. With"numpy"each table is adictof 1-D arrays andXa 2-D array (objectdtype when it mixes types). - random_state (
int, RandomState instance or None): Seed for the generation. Pass an int for reproducible output.
Returns:
- database (
Database): The relational data. - X (
DataFrame or ndarray of shape (n_samples, 1 or 2)): Population table:customer_idand, withwith_time=True,cutoff.n_samples = n_entities * n_cutoffs. - y (
ndarray of shape (n_samples,)): Integer class labels. - rule (
str): The generating rule. Only returned withreturn_rule=True.
Raises:
ValueError: Ifsignalis unknown, ifn_cutoffs > 1withoutwith_time=Trueor if a parameter is out of range.ImportError: Ifoutputnames a library that is not installed.
See Also
sklink.datasets.make_relational_regression : The same tables with a numeric target. sklink.datasets.load_shop : A small, fixed example database.
Notes
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,meanandsumover a path of table names joined by.starting at the entity, such asordersororders.order_items.products. A column follows the path, as inmean(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, sofloat(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:
>>> 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
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): 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): What the target is, beforenoise. Every aggregate is defined for customers without rows:"root": a linear combination of thex_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 pluscount(orders[type == 'pickup'])plus the conditional count.n_informative_root (
int or None): Number ofx_root_*columns the root formula uses.Nonemeans 2 for"root"and"mixed"and 0 otherwise.n_noise_root (
int): Number ofnoise_root_*columns ofcustomers.n_noise_child (
int): Number ofnoise_child_*columns oforders.n_noise_tables (
int): Number of extra child tables ofcustomerswithout signal.noise (
float): Standard deviation of the Gaussian noise added to the target.with_time (
bool): Addorders.created_atand thecutoffcolumn ofX; the target uses only the orders created before the cutoff. Seemake_relational_classification.n_cutoffs (
int): Number of cutoffs. Values above 1 needwith_time=True.missing_rate (
float): Fraction of missing values in the non-key columns ofordersand of the noise tables.orphan_rate (
float): Fraction of rows ofordersand of the noise tables whosecustomer_iddoes not exist incustomers.return_rule (
bool): Also return the target formula as a string, in the format described inmake_relational_classification, without a threshold.output (
('auto', 'pandas', 'polars', 'pyarrow', 'numpy')): Format of the tables and ofX.random_state (
int, RandomState instance or None): Seed for the generation. Pass an int for reproducible output.
Returns:
- database (
Database): The relational data. - X (
DataFrame or ndarray of shape (n_samples, 1 or 2)): Population table:customer_idand, withwith_time=True,cutoff. - y (
ndarray of shape (n_samples,)): Float target. - rule (
str): The target formula. Only returned withreturn_rule=True.
Raises:
ValueError: Ifsignalis unknown, ifn_cutoffs > 1withoutwith_time=Trueor if a parameter is out of range.ImportError: Ifoutputnames a library that is not installed.
See Also
sklink.datasets.make_relational_classification : The same tables with class labels. sklink.datasets.load_shop : A small, fixed example database.
Examples:
>>> 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')