sklink
Relational machine learning on multi-table data, compatible with scikit-learn.
Modules:
- cluster: Clustering of the entities of a multi-table database.
- compose: Combine relational estimators with scikit-learn transformers of tables.
- database: Relational databases: tables, keys, relationships and their schema.
- datasets: Synthetic relational datasets and a small bundled example database.
- engine: Evaluation of expressions on a database: the only layer that reads data.
- ensemble: Ensembles of relational models: forests, gradient boosting, isolation forests.
- exceptions: Exceptions and warnings raised by scikit-link.
- expressions: Expressions: the shared language of relational features.
- feature_extraction: Turn relational data into flat feature matrices for any estimator.
- inspection: Read what a relational model learned, in terms of tables and columns.
- model_selection: Validation tools for relational data.
- plotting: Figures that show what a relational model reads, learns and predicts.
- primitives: Aggregation primitives: what an expression computes over related rows.
- tree: Decision trees that ask about aggregates of related tables.
- utils: Validation helpers and reusable checks for relational estimators.
Classes:
- Database: Immutable, validated relational database used by scikit-link estimators.
- Relationship: A foreign key of a child table that references the primary key of a parent.
- Schema: Immutable, data-free description of a database.
Functions:
- config_context: Temporarily change the configuration inside a
withblock. - detach: Return a copy of a model in which every database keeps only its schema.
- get_config: Return a copy of the current configuration.
- rebind: Return a copy of a model that uses
databaseinstead of its current one. - set_config: Set resource options for the current thread.
- show_versions: Print the versions of scikit-link, its dependencies and the platform.
sklink.Database
Database(tables: Mapping[str, Any], *, primary_keys: Mapping[str, str | Sequence[str] | None], relationships: Sequence[RelationshipLike] = (), time_columns: Mapping[str, str] | None = None, column_types: Mapping[str, Mapping[str, SemanticType]] | None = None, exclude: Mapping[str, Sequence[str]] | None = None, orphans: Literal['error', 'warn', 'ignore'] = 'error', validate: Literal['full', 'schema', 'none'] = 'full') -> NoneImmutable, validated relational database used by scikit-link estimators.
A Database holds several tables linked by primary and foreign keys. It is passed to estimators as the database hyperparameter, while X holds one row per sample with the key of the entity to predict for. The object is never copied: sklearn.base.clone, copy.copy and copy.deepcopy return the same instance.
Time is optional. Declare time_columns only when rows become available at a given time and the estimator receives a cutoff (time=).
Guides: Describe your database, Load relational data
Parameters:
- tables (
mapping of str to table): Each table is a pandas, Polars or PyArrow table, a mapping of column name to one-dimensional array, or the path of a Parquet file. - primary_keys (
mapping of str to str, sequence of str or None): Primary key column(s) of every table.Nonedeclares a table without a key, which cannot be the parent of a relationship. - relationships (
sequence of Relationship or (child, parent) tuples): Foreign keys, written child first:("orders.customer_id", "customers.id"). - time_columns (
mapping of str to str): Datetime column that tells when each row of a table becomes available. - column_types (
mapping of str to mapping of str to str): Override inferred semantic types ("numeric","categorical","boolean","datetime","text"or"id") per table and column. Numeric values are stored asfloat64: an integer column with values beyond2**53in absolute value raises unless it is declared here, as"id"or"categorical"to keep it exact, or as"numeric"to accept rounding to the nearestfloat64. Strings that average 30 characters or more and are nearly all distinct (at least 100 distinct values and 90% of the present ones), such as reviews or descriptions, are inferred as"text"and feed no feature; declare them"categorical"to aggregate them as categories, or declare the type of a column near those limits so that every snapshot of the data reads it the same way. Columns of a categorical type (pandasCategorical, PolarsCategoricalorEnum, Arrow dictionaries, also in Parquet files when PyArrow is installed) stay categorical. - exclude (
mapping of str to sequence of str): Columns that must never feed a feature. - orphans (
(error, warn, ignore)): What to do with non-null foreign keys that have no parent row: raiseIntegrityError, emit aSklinkWarningwith the number of rows, or keep them silently. - validate (
(full, schema, none)):"full"checks keys and orphans."schema"and"none"skip the checks that scan data; with them, unique and non-null keys are the caller's responsibility. The declarations themselves (tables, columns, keys and relationships that exist and have compatible types) are always checked, because every later step relies on them, so"none"currently behaves like"schema".
Attributes:
- schema (
Schema): Data-free description of tables, keys and relationships. - table_names (
tuple of str): Names of the tables. - fingerprint (
str): Identity of this object and its content, used as cache key.
See Also
sklink.Schema : Data-free description of the tables, keys and relationships. sklink.Relationship : One foreign key between two tables. sklink.detach : Remove the databases of a fitted model before saving it. sklink.datasets.load_shop : A small example database.
Notes
The tables are read into canonical storage when the object is built. Changing the original data frames or files afterwards is undefined behaviour: build a new Database (or use with_tables) instead.
A database built only from Parquet files is pickled as a reference to its files, which are read again when it is loaded. A database held in memory is pickled with its data and emits a PerformanceWarning once above sklink.set_config(warn_pickle_bytes=...); use sklink.detach before saving a fitted model.
Loading a pickled database in a process that already holds a database with the same fingerprint returns that object instead of a copy. A model pickled and loaded again, or returned by a joblib worker process (cross_validate(..., n_jobs=2, return_estimator=True)), shares the original database, as clone and copy do.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([1, 2, 3])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 3]),
... "amount": np.array([5.0, 7.5, 3.0]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> db.n_rows("orders")
3Functions:
- describe: Return a summary of tables, columns and relationships, without data.
- from_parquet_dir: Build a database from one Parquet file per table and a schema.
- n_rows: Return the number of rows of a table.
- table: Return the data of a table as a new object.
- with_tables: Return a new database with some tables replaced and the same declarations.
sklink.Database.describe
describe(*, statistics: bool = False) -> dict[str, Any]Return a summary of tables, columns and relationships, without data.
Parameters:
- statistics (
bool): Add the fan-out of every relationship, computed from its key index. The statistics count rows; they never contain row values.
Returns:
- description (
dict):"tables"maps every table name to a dict with"n_rows","primary_key"(list of column names orNone),"time_column"(name orNone) and"columns"(column name to semantic type)."relationships"lists one dict per relationship with"name","child_table","child_columns","parent_table"and"parent_columns".
With statistics=True every relationship dict also has "statistics", a dict with these keys. Children are the child rows whose foreign key matches a parent row.
"min","max"(int) and"mean"(float): number of children per parent row, over every row of the parent table, including those without children.Nonewhen the parent table is empty."n_parents_without_children"(int): parent rows with no child."n_orphans"(int): child rows whose foreign key is not null (no component is null) and matches no parent row. Rows with a null foreign key have no parent and are not orphans."children_per_parent"(list of[n_children, n_parents]pairs of int): histogram of the number of children per parent row, sorted byn_children, with only the counts that occur (n_parents > 0). It holds at most 32 pairs. When more than 32 distinct counts occur, the first 31 are kept and the last pair[k, n]counts thenparent rows withkor more children; this happens exactly whenkis less than"max". Then_parentsadd up to the number of parent rows.
The statistics depend only on the content of the tables, not on the order of their rows.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([1, 2, 3])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 3]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> db.describe()["tables"]["orders"]["n_rows"]
3
>>> stats = db.describe(statistics=True)["relationships"][0]["statistics"]
>>> stats["min"], stats["max"], stats["mean"], stats["n_orphans"]
(0, 2, 1.0, 0)
>>> stats["children_per_parent"]
[[0, 1], [1, 1], [2, 1]]sklink.Database.fingerprint
fingerprint: strIdentity of this object and its content, used as cache key.
sklink.Database.from_parquet_dir
from_parquet_dir(path: str | os.PathLike[str], *, schema: Schema | str | os.PathLike[str]) -> DatabaseBuild a database from one Parquet file per table and a schema.
Parameters:
- path (
str or path - like): Folder with a<table>.parquetfile for every table of the schema. - schema (
Schema, JSON string or path of a JSON file): The schema, as written bySchema.to_json.
Returns:
- database (
Database):
sklink.Database.n_rows
n_rows(table: str) -> intReturn the number of rows of a table.
sklink.Database.schema
schema: SchemaData-free description of the database.
sklink.Database.table
table(name: str, *, output: Output = 'auto') -> AnyReturn the data of a table as a new object.
The columns keep their order, their type as read (integer, float, boolean, string or datetime with its unit), their missing values and the timezone of timezone-aware datetimes. Rows come in the canonical order of the database: sorted by primary key, or by every column for a table without one. The result never shares memory with the database, so changing it changes neither the database nor its fingerprint.
Parameters:
- name (
str): Name of the table. - output (
(auto, pandas, polars, pyarrow, numpy)): Format of the result, as insklink.datasets."auto"gives a pandasDataFramewhen pandas is installed and NumPy otherwise."numpy"gives adictof column name to one-dimensionalndarray.
Returns:
- table (
(DataFrame, DataFrame, Table or dict)): The table's data.
Raises:
SchemaError: If the database has no tablename.ValueError: Ifoutputis not one of the accepted values.ImportError: Ifoutputnames a library that is not installed.
Notes
Polars and PyArrow hold missing values as nulls in a column of the original type. NumPy has no null for every type, so with "numpy" and "pandas" a missing value is NaN in floats and NaT in datetimes; a numeric column of integer type with missing values becomes float64 with NaN, and any other column with missing values (keys, strings, booleans) an object column with None. Strings are object columns. NumPy datetimes have no timezone: with "numpy" a timezone-aware column is returned in UTC, and its timezone is in schema.
Key columns (primary and foreign keys) hold the normalized values the database matches on: int64 for integers (including integral floats), float64 for other numbers and strings otherwise.
Numeric columns are stored as float64, as the features computed from them. Integers beyond 2**53 in absolute value are refused unless the column is declared in column_types: as "id" or "categorical" they stay exact; declared "numeric", they come back rounded to the nearest float64.
Examples:
>>> import numpy as np
>>> from sklink import Database
>>> db = Database(
... tables={
... "customers": {"customer_id": np.array([2, 1])},
... "orders": {
... "order_id": np.array([10, 11, 12]),
... "customer_id": np.array([1, 1, 2]),
... "amount": np.array([5.0, np.nan, 3.0]),
... },
... },
... primary_keys={"customers": "customer_id", "orders": "order_id"},
... relationships=[("orders.customer_id", "customers.customer_id")],
... )
>>> orders = db.table("orders", output="numpy")
>>> list(orders)
['order_id', 'customer_id', 'amount']
>>> orders["amount"]
array([ 5., nan, 3.])
>>> db.table("customers", output="numpy")["customer_id"]
array([1, 2])sklink.Database.table_names
table_names: tuple[str, ...]Names of the tables.
sklink.Database.with_tables
with_tables(**tables: Any) -> DatabaseReturn a new database with some tables replaced and the same declarations.
Parameters:
- **tables (
Any): New data for existing tables, by name.
Returns:
- database (
Database): A new object, with a new fingerprint.
sklink.Relationship
Relationship(child: str | tuple[str, ...], parent: str | tuple[str, ...], name: str | None = None) -> NoneA foreign key of a child table that references the primary key of a parent.
Parameters:
- child (
str or sequence of str):"table.column"of the foreign key, or several for a composite key. - parent (
str or sequence of str):"table.column"of the referenced primary key, in the same order. - name (
str): Unique name. Defaults to"{child_table}.{child_column}->{parent_table}".
Examples:
>>> from sklink import Relationship
>>> rel = Relationship("orders.customer_id", "customers.id")
>>> rel.name, rel.child_table, rel.parent_table
('orders.customer_id->customers', 'orders', 'customers')Functions:
- from_dict: Build a relationship from
to_dictoutput. - to_dict: Return a JSON-serializable description.
Attributes:
- child (
str | tuple[str, ...]): - child_columns (
tuple[str, ...]): - child_table (
str): - key (
str): Name of the relationship, neverNoneafter construction. - name (
str | None): - parent (
str | tuple[str, ...]): - parent_columns (
tuple[str, ...]): - parent_table (
str):
sklink.Relationship.child
child: str | tuple[str, ...]sklink.Relationship.child_columns
child_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)sklink.Relationship.child_table
child_table: str = field(init=False, repr=False, compare=False)sklink.Relationship.from_dict
from_dict(data: Mapping[str, Any]) -> RelationshipBuild a relationship from to_dict output.
sklink.Relationship.key
key: strName of the relationship, never None after construction.
sklink.Relationship.name
name: str | None = Nonesklink.Relationship.parent
parent: str | tuple[str, ...]sklink.Relationship.parent_columns
parent_columns: tuple[str, ...] = field(init=False, repr=False, compare=False)sklink.Relationship.parent_table
parent_table: str = field(init=False, repr=False, compare=False)sklink.Relationship.to_dict
to_dict() -> dict[str, Any]Return a JSON-serializable description.
sklink.Schema
Schema(tables: Iterable[TableSchema], relationships: Iterable[Relationship] = ()) -> NoneImmutable, data-free description of a database.
A schema lists tables, their columns with semantic types, primary keys, optional time columns and relationships. It holds no data and no statistics, and round-trips through JSON.
Parameters:
- tables (
iterable of TableSchema): Table descriptions. - relationships (
iterable of Relationship): Foreign keys between tables.
Examples:
>>> from sklink import Schema
>>> from sklink.datasets import load_shop
>>> schema = load_shop().database.schema
>>> schema
Schema(tables=['customers', 'orders', 'order_items', 'products'], relationships=3)
>>> schema.table("orders").column("type").semantic_type
'categorical'
>>> Schema.from_json(schema.to_json()) == schema
TrueFunctions:
- children_of: Relationships whose parent is
table(one-to-many fromtable). - from_dict: Build a schema from
to_dictoutput. - from_json: Read a schema written by
to_json. - missing_from: List what this schema uses and
otherlacks (tables, columns, links). - parents_of: Relationships whose child is
table(many-to-one fromtable). - relationship: Return a relationship by name, or raise
SchemaError. - subset: Return the schema restricted to some tables and relationships.
- table: Return a table schema, or raise
SchemaError. - to_dict: Return a JSON-serializable description with
format_version. - to_json: Serialize to a JSON string.
Attributes:
- relationships (
tuple[Relationship, ...]): Relationships, in declaration order. - table_names (
tuple[str, ...]): Names of the tables, in declaration order.
sklink.Schema.children_of
children_of(table: str) -> tuple[Relationship, ...]Relationships whose parent is table (one-to-many from table).
sklink.Schema.from_dict
from_dict(data: Mapping[str, Any]) -> SchemaBuild a schema from to_dict output.
sklink.Schema.from_json
from_json(text: str) -> SchemaRead a schema written by to_json.
sklink.Schema.missing_from
missing_from(other: Schema) -> list[str]List what this schema uses and other lacks (tables, columns, links).
sklink.Schema.parents_of
parents_of(table: str) -> tuple[Relationship, ...]Relationships whose child is table (many-to-one from table).
sklink.Schema.relationship
relationship(name: str) -> RelationshipReturn a relationship by name, or raise SchemaError.
sklink.Schema.relationships
relationships: tuple[Relationship, ...]Relationships, in declaration order.
sklink.Schema.subset
subset(tables: Iterable[str], relationships: Iterable[str]) -> SchemaReturn the schema restricted to some tables and relationships.
sklink.Schema.table
table(name: str) -> TableSchemaReturn a table schema, or raise SchemaError.
sklink.Schema.table_names
table_names: tuple[str, ...]Names of the tables, in declaration order.
sklink.Schema.to_dict
to_dict() -> dict[str, Any]Return a JSON-serializable description with format_version.
sklink.Schema.to_json
to_json() -> strSerialize to a JSON string.
sklink.config_context
config_context(**new_config: Any) -> Iterator[None]Temporarily change the configuration inside a with block.
Parameters:
- **new_config (
Any): Same keywords asset_config.
Examples:
>>> import sklink
>>> with sklink.config_context(cache_bytes=0):
... sklink.get_config()["cache_bytes"]
0sklink.detach
detach(estimator: T) -> TReturn a copy of a model in which every database keeps only its schema.
Use it before pickling a fitted model so that the file contains no table data, then call rebind after loading. The original object is not modified.
Guides: Save, load and deploy
Parameters:
- estimator (
(estimator, pipeline or meta - estimator)): Any object, fitted or not, that references aDatabase.
Returns:
- detached (
same type as): A copy whose databases are replaced by schema-only placeholders.estimator
See Also
sklink.rebind : Bind a database to the model again after loading it.
Examples:
>>> import pickle
>>> import sklink
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> saved = pickle.dumps(sklink.detach(tree))
>>> loaded = pickle.loads(saved)
>>> loaded.database
DetachedDatabase(tables=['customers', 'orders', 'order_items', 'products'])
>>> loaded = sklink.rebind(loaded, shop.database)
>>> loaded.predict(shop.X[:5])
array([1, 1, 1, 1, 0])sklink.get_config
get_config() -> dict[str, Any]Return a copy of the current configuration.
Returns:
- config (
dict): Keys are the parameters ofset_config.
Examples:
>>> import sklink
>>> sklink.get_config()["backend"]
'numpy'sklink.rebind
rebind(estimator: T, database: Database) -> TReturn a copy of a model that uses database instead of its current one.
The fitted state is kept. The new database must contain every table, column and relationship that the fitted model uses; extra ones are allowed.
Guides: Save, load and deploy
Parameters:
- estimator (
(estimator, pipeline or meta - estimator)): A model that references aDatabaseor a detached placeholder. - database (
Database): The database to use from now on.
Returns:
- rebound (
same type as):estimator
Raises:
SchemaError: Ifdatabaselacks something the fitted model uses.
See Also
sklink.detach : Remove the databases of a model before saving it.
Examples:
>>> import pickle
>>> import sklink
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> saved = pickle.dumps(sklink.detach(tree))
>>> loaded = pickle.loads(saved)
>>> loaded.database
DetachedDatabase(tables=['customers', 'orders', 'order_items', 'products'])
>>> loaded = sklink.rebind(loaded, shop.database)
>>> loaded.predict(shop.X[:5])
array([1, 1, 1, 1, 0])sklink.set_config
set_config(*, backend: str | None = None, cache_bytes: int | None = None, engine_threads: int | None = None, chunk_rows: int | None = None, warn_pickle_bytes: int | None = None, tree_kernels: str | None = None) -> NoneSet resource options for the current thread.
Parameters left as None keep their current value. Environment variables with the SKLINK_ prefix (SKLINK_CACHE_BYTES...) provide the initial values.
Guides: Fit faster
Parameters:
- backend (
str): Name of the evaluation backend."numpy"is the in-memory reference. - cache_bytes (
int): Size of the expression cache in bytes.0disables it. - engine_threads (
int): Threads used by the engine. - chunk_rows (
int): Number of population rows evaluated at once bytransformandpredict. - warn_pickle_bytes (
int): Size above which pickling an in-memory database emits aPerformanceWarning. - tree_kernels (
(auto, numpy, numba)): Implementation of the inner loops of relational trees, forests and gradient boosting."auto"(the initial value) compiles them with Numba when it is installed (a dependency where Numba has wheels) and supported, and uses NumPy otherwise;"numpy"always uses NumPy;"numba"requires Numba. Both give exactly the same models and predictions. Forests read it whenfitstarts and pass it to their workers.
Examples:
>>> import sklink
>>> previous = sklink.get_config()["chunk_rows"]
>>> sklink.set_config(chunk_rows=10_000)
>>> sklink.get_config()["chunk_rows"]
10000
>>> sklink.set_config(chunk_rows=previous)sklink.show_versions
show_versions() -> NonePrint the versions of scikit-link, its dependencies and the platform.
Paste the output into bug reports. Optional dependencies that are not installed are listed as not installed. Nothing is imported to build the report: versions are read from the installed package metadata.
Examples:
>>> import sklink
>>> sklink.show_versions()
System:
...