Machine learning
on related tables.
Customers and orders, patients and visits, machines and sensor readings: keep each in its own table, and learn from the related rows of every entity with the scikit-learn API.
pip install "scikit-link[pandas]"01 · The idea
One row per entity
An entity, such as a customer, can have many related rows, such as orders. Follow the marked customer through both tables to see how two purchases become one feature.
customers
| PKcustomer_id | country |
|---|---|
| c07 | CO |
| c12 | MX |
orders
| FKcustomer_id | amount |
|---|---|
| c07 | 24 |
| c12 | 42 |
| c07 | 36 |
features
| customer_id | mean_amount |
|---|---|
| c07 | 30 |
| c12 | 42 |
02 · Two ways to use it
Compute features or fit a relational tree
- Relational features.
RelationalFeaturizercomputes one feature row per sample. Use it in aPipelinewith a tabular estimator such as gradient boosting. - Relational trees, forests and gradient boosting. A split can learn which related rows to count and how many are enough to take a branch.
Run data.py first, then paste either example into the same session. db holds the related tables, X has one row per customer, and y holds the labels.
from sklink.datasets import make_relational_classification
# A Database of customers, orders, order items and products, and X with one
# row per customer. Build your own with sklink.Database(tables=...,
# primary_keys=..., relationships=[("orders.customer_id", "customers.customer_id")]).
db, X, y = make_relational_classification(1000, signal="conditional", random_state=0)from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklink.feature_extraction import RelationalFeaturizer
pipe = make_pipeline(
RelationalFeaturizer(db, entity="customers", key="customer_id"),
HistGradientBoostingClassifier(),
)
print(f"accuracy {cross_val_score(pipe, X, y, cv=5).mean():.3f}")from sklink.inspection import export_text
from sklink.tree import RelationalDecisionTreeClassifier
tree = RelationalDecisionTreeClassifier(
db, entity="customers", key="customer_id", max_depth=2
)
print(export_text(tree.fit(X, y)))accuracy 0.960
|--- exists(orders[amount > 100.06 & type == 'express']) <= 0.500
| |--- class: 0
|--- exists(orders[amount > 100.06 & type == 'express']) > 0.500
| |--- class: 103 · Rules you can read
Read a tree split
This illustrative tree, not the one fitted above, first counts each customer's express orders above 137.5. Customers with three or more follow the right branch to premium; the others are split again by country.
count(orders[amount > 137.5 & type == 'express']) > 2.5country in {'CO', 'PE'}04 · How it works
From a database to a fitted estimator
Pass the database to the estimator and the sample rows to fit. Cross-validation splits the sample rows while each estimator keeps a reference to the database.
- 1
Describe the tables
Tables, primary keys and relationships go into an immutable
Database.Xkeeps one row per sample.orders.customer_id → customers.customer_id - 2
Search aggregations
Follow table relationships to compute counts, means, modes and shares. An aggregation can use only rows that meet a condition.
mean(orders.amount[type == 'express']) - 3
Fit any estimator
Use the features with gradient boosting, or fit a relational tree or forest. Tune either workflow with
GridSearchCV.GridSearchCV(forest, param_grid, cv=5)
Training and evaluation
During fit, estimators learn feature definitions, categories and split thresholds from rows reachable from the training samples.
Features at a point in time
If events arrive over time, give each sample a cutoff and declare the event timestamp columns. Features then use only events strictly before that sample's cutoff. Static data can omit dates.
Learn more
- What is relational machine learning?How models use related tables and where information can leak during evaluation.
- Compared with other toolsFeaturetools, getML, skrub and relational deep learning, and when to use each one.
- BenchmarksDatasets, training splits and tuning budgets for comparisons with flattened-table baselines.
- RoadmapFirst release: a relational featurizer, relational trees, forests and gradient boosting, clustering and anomaly detection.
- Introducing scikit-linkWhy the project exists and what comes first.
Working with multi-table data?
Share your table schema, the entity you predict for and the target you want to model.