Skip to content

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.

bash
pip install "scikit-link[pandas]"
A coral thread traces one sample through two related tables to a neighborhood on the feature map.A coral thread traces one sample through two related tables to a neighborhood on the feature map.

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.

customersentity

PKcustomer_idcountry
c07CO
c12MX

ordersrelated

FKcustomer_idamount
c0724
c1242
c0736

featuresone row per customer

customer_idmean_amount
c0730
c1242
For customer c07, the mean order amount is (24 + 36) / 2 = 30.

02 · Two ways to use it

Compute features or fit a relational tree

  1. Relational features. RelationalFeaturizer computes one feature row per sample. Use it in a Pipeline with a tabular estimator such as gradient boosting.
  2. 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.

python
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)
python
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}")
python
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)))
text
accuracy 0.960
|--- exists(orders[amount > 100.06 & type == 'express']) <= 0.500
|   |--- class: 0
|--- exists(orders[amount > 100.06 & type == 'express']) >  0.500
|   |--- class: 1

03 · 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.

splitcount(orders[amount > 137.5 & type == 'express']) > 2.5
no
splitcountry in {'CO', 'PE'}
yesstandard
nopremium
yes
prediction premium 3 express orders above 137.5
Each split reads as a sentence about the related rows. The coral path is the prediction for one customer.

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. 1

    Describe the tables

    Tables, primary keys and relationships go into an immutable Database. X keeps one row per sample.

    orders.customer_id → customers.customer_id
  2. 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. 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

Working with multi-table data?

Share your table schema, the entity you predict for and the target you want to model.

Released under the MIT License.