Core concepts
Decide what one prediction represents before you describe the tables: a customer, a patient, a machine, an account. One row of X identifies that entity, and a Database holds its table and the related records you can look up for that row. The examples below use customers and orders.
The database
Each table needs a primary key that identifies a single row. An order_id identifies an order. Its customer_id is a foreign key that can repeat across orders. Declare the foreign key first in the relationship, followed by the primary key it refers to.
import pandas as pd
from sklink import Database
customers = pd.DataFrame({"customer_id": [1, 2, 3], "country": ["CO", "PE", "MX"]})
orders = pd.DataFrame(
{
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 2, 3],
"type": ["express", "standard", "express", "pickup"],
"amount": [120.0, 35.5, 80.0, 15.0],
}
)
db = Database(
tables={"customers": customers, "orders": orders},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
)
print(db.schema)Schema(tables=['customers', 'orders'], relationships=1)Give this database to the estimator's constructor; the samples go to fit(X, y), as the next section shows. When cross-validation clones the estimator, the clones share the immutable tables and only split X.
Each column gets a semantic type, inferred from its values: numeric, categorical, boolean, datetime, text or id. Keys are id and are never aggregated as numbers.
print(db.describe()["tables"]["orders"]["columns"]){'order_id': 'id', 'customer_id': 'id', 'type': 'categorical', 'amount': 'numeric'}The entity and the population table X
The entity is the kind of thing you predict for, such as a customer. Its rows live in the entity table, here customers, which the entity= parameter names. X is the population table (other pages simply call it X): one row per sample, with the key of the entity in a column. It is what you pass to fit, predict and cross_val_score, so cross-validation splits the samples in X while the estimator keeps its reference to the database.
X = pd.DataFrame({"customer_id": [1, 2, 3]})
y = [1, 0, 0]The three rows above request three predictions. Customer 1 has two order rows (10 and 11), so their order count is 2. If X contains the same key twice, the result also has two rows for that key, in their original positions. Keep the target in y, aligned with X.
X can hold more columns than the key. With passthrough=True (the default) the featurizer keeps them as features, and the trees use them as ordinary columns.
Expressions and canonical names
Every relational feature, and every question a relational tree asks, is an expression: a value per sample computed by following relationships from the entity. Its canonical name says how it is computed, and it reads back to the same expression.
| Canonical name | Meaning |
|---|---|
count(orders) | Number of orders of the customer |
mean(orders.amount) | Mean amount of those orders |
count(orders[type == 'express']) | Number of express orders |
mean(orders.amount[type == 'express']) | Mean amount of the express orders |
count(orders[amount > 137.5 & type == 'express']) | Express orders above 137.5 |
mode(orders.order_items.products.category) | Most frequent category of the products bought: two hops to the order lines, then a lookup of each line's product (both explained below) |
count(orders.order_items[products.category == 'toys']) | Order lines whose product is a toy: the condition looks up each line's product |
country | A column of the entity table itself, written without a path |
Read mean(orders.amount[type == 'express']) from the inside out. Follow the customer key to orders, keep the express orders, then average their amount. In the example above, customer 1 has two orders but only order 10 is express, so the mean is 120.0. mean is the primitive, the aggregation applied to those rows. A longer path such as orders.order_items.products follows more keys, as in the shop diagram. A condition can also read a column of the row each aggregated row points to, such as the product of an order line in count(orders.order_items[products.category == 'toys']).
A hop follows a relationship from a table to its child rows: orders.order_items is two hops, and max_relationship_depth (default 2) caps them. A lookup follows a relationship from each aggregated row to the single row it points to, as products. does inside that condition and in mode(orders.order_items.products.category). It adds no rows, is not a hop, and max_lookup_depth (default 1) caps it.
The built-in primitives include count, exists (1 when any row matches, else 0), sum, mean, min, max, mode, nunique and proportion, and, with a time column, time_since_last and time_since_first in days. The custom primitives tutorial lists them all.
The same expression has the same name across fits. The set of expressions can change when training customers have different categories or a tree learns a different threshold.
Two ways to learn from related tables
RelationalFeaturizer | Relational trees, forests and boosting | |
|---|---|---|
| What it is | A transformer | Classifiers and regressors |
During fit | Builds a feature catalog using the schema and rows reachable from training samples | Searches for a split at each node using the training labels |
| Conditions inside aggregates | Counts frequent categories and, by default (conditional=True), computes numeric aggregates within each category of columns that have at most max_categories categories. | Can learn category and numeric conditions together, up to max_conditions. |
| What you get | A matrix you can use with a tabular estimator | A fitted classifier or regressor with predict |
Both read the same database and use the same canonical names, so you can start with one and compare it with the other.
Leakage and what fit sees
Imagine a delivery type that occurs only on orders from held-out customers. If all customers help choose the categories, the feature catalog already contains information from the test fold. Fit the featurizer inside a pipeline so each fold learns its own catalog.
✕ Feature catalog fitted before splitting
A category seen only for c05 or c06 can enter the catalog used for evaluation.
✓ Feature catalog fitted on the training fold
Transform c05 and c06 with that catalog. Their orders can supply feature values during prediction.
- Learned state comes from the training samples only. Category vocabularies of the featurizer, and the bins and conditions of the trees, are computed in
fitfrom the rows reachable from the samples ofXpassed tofit. In cross-validation, the test fold never shapes the features. - A sample only reads its own related rows. Paths go from the entity to its children, and up to parents such as
products. A path that goes back down from a product to all of its order lines would read other customers' orders; such reverse paths are off unless you setallow_reverse_paths=True.
Static and temporal mode
If the tables already describe what you know at prediction time, use them as they are. When the database also holds later orders, specify the order time in the database and put a prediction cutoff in each row of X.
db_t = Database(
tables={
"customers": customers,
"orders": orders.assign(
created_at=pd.to_datetime(
["2024-01-05", "2024-03-01", "2024-02-10", "2024-04-20"]
)
),
},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
time_columns={"orders": "created_at"},
)
X_t = pd.DataFrame(
{"customer_id": [1, 2, 3], "cutoff": pd.to_datetime(["2024-02-01"] * 3)}
)Two settings work together. time_columns on the Database says when each order happened. time on the estimator names the column of X that holds each sample's cutoff, the date the prediction is made. Only orders dated strictly before a row's cutoff are visible to it.
from sklink.tree import RelationalDecisionTreeClassifier
tree = RelationalDecisionTreeClassifier(
db_t, entity="customers", key="customer_id", time="cutoff"
).fit(X_t, y)For customer 1 and the February 1 cutoff, the January 5 order is visible and the March 1 order is excluded. The time and cutoffs tutorial covers windows, time_since_last and TemporalCutoffSplit.
Next steps
- Describe your own database: keys, types, exclusions and orphan rows.
- From your own tables to X and y: one row per prediction, cutoffs and a label without leakage.
- Relational features: choose which tables and aggregations your transformer can use.
- API reference: every public class and function.