This is the development version.
Skip to content

Relational features for any scikit-learn model ​

Put RelationalFeaturizer before a tabular estimator in a scikit-learn pipeline. It follows the relationships for each sample in X and turns the related rows into feature values such as a mean order amount.

For a small example, follow customer c07 from its key to its two orders. A mean reduces those two amounts to one feature value. The model sees a matrix with one row per sample, in the order of X.

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.

A problem with a known rule ​

Now use a synthetic dataset with customers, orders, order items and products. X contains one customer_id per sample, and y contains the corresponding class labels. Request the rule so you can compare the generated features with what actually determines the label.

python
from sklink.datasets import make_relational_classification

db, X, y, rule = make_relational_classification(
    n_entities=1000, signal="conditional", return_rule=True, random_state=0
)
print(rule)
print(db.table_names)
text
count(orders[amount > 100.0 & type == 'express']) >= 1
('customers', 'orders', 'order_items', 'products')

A customer is in class 1 when they have at least one express order above 100. The two conditions must hold on the same order. Counting express orders and counting expensive orders separately loses that detail.

Default features ​

entity="customers" chooses the table every path starts from, and key="customer_id" names the column of X that holds its key. fit builds a catalog of expressions from the schema and the rows it can reach from the training samples. transform evaluates that catalog on any compatible X.

python
from sklink.feature_extraction import RelationalFeaturizer

featurizer = RelationalFeaturizer(
    db, entity="customers", key="customer_id", max_relationship_depth=2
)
featurizer.fit(X)
names = featurizer.get_feature_names_out()
print(featurizer.n_features_out_)
print(names[[2, 7, 20, 40]])
text
126
['count(orders)' "count(orders[type == 'economy'])"
 "mean(orders.amount[type == 'economy'])"
 "mean(orders.noise_child_2[type == 'pickup'])"]

n_features_out_ is the size of the fitted catalog. Each name identifies an output column. By default, transform returns a NumPy array of floats. Categorical values appear as integer codes in that array. categorical_features_ marks those columns, and categories_ tells you which label each code represents.

python
print(names[featurizer.categorical_features_])
print(featurizer.categories_["mode(orders.type)"])
text
['mode(orders.noise_child_1)' 'mode(orders.type)'
 'mode(orders.order_items.products.category)']
['economy' 'express' 'pickup' 'standard']

In a pipeline ​

Inside a pipeline, cross-validation refits the featurizer on each training fold. Category vocabularies are learned only from rows reachable from the training samples.

python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

pipe = make_pipeline(
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=2,
        conditional=False,
    ),
    HistGradientBoostingClassifier(random_state=0),
)
print(f"{cross_val_score(pipe, X, y, cv=5).mean():.3f}")
text
0.624

Mean cross-validation accuracy is modest without conditional aggregates. The pipeline can use values such as an overall mean and the number of express orders, so it has only indirect evidence about the joint condition.

Conditional aggregates ​

By default, conditional=True adds means and sums of numeric columns within each category of the categorical columns that have at most max_categories categories. With a list of primitives, it uses the ones of mean and sum that the list names. For example, mean(orders.amount[type == 'express']) gives the model the average amount among each customer's express orders.

python
pipe = make_pipeline(
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=2,
    ),
    HistGradientBoostingClassifier(random_state=0),
)
print(f"{cross_val_score(pipe, X, y, cv=5).mean():.3f}")
text
0.960

Mean accuracy rises sharply on this dataset. The extra columns give the model amount and order type together. The catalog can also grow quickly. max_categories (default 10) caps how many frequent categories of each column get their own counts; a column with more categories gets no conditional means or sums. Pass conditional=False for the smallest catalog.

Control the catalog ​

Limit which paths and expressions the featurizer considers.

  • max_relationship_depth: how many relationships a path may follow. Depth 1 reads orders, depth 2 also reaches order_items through orders, and depth 3 makes products part of the path.
  • max_lookup_depth: how many many-to-one steps a path of full depth may take from each of its rows to the row it points to, such as from an order line to its product. With the default 1 and depth 2, the order items are counted by the category of their product, as in count(orders.order_items[products.category == 'toys']), and the product columns are aggregated, as in mean(orders.order_items.products.price); 0 turns this off.
  • primitives: "default" picks aggregations from each column's type, and in temporal mode adds last and trend for the numeric columns of tables with a time column. A list limits the aggregations to those, as in ["count", "mean", "sum"]. The entity table's own columns, and count and proportion for each frequent category, are still added; max_categories=0 drops the per-category ones.
  • include and exclude: glob patterns over canonical names, table names or relationship names.
  • max_features: a safety limit. Fitting fails with a clear message when the catalog is larger, instead of computing thousands of columns.
python
for params in [
    {"max_relationship_depth": 1},
    {"max_relationship_depth": 2, "primitives": ["count", "mean"]},
    {"max_relationship_depth": 2, "include": ["*orders.amount*"]},
    {"max_relationship_depth": 2, "exclude": ["*noise*"]},
]:
    small = RelationalFeaturizer(
        db, entity="customers", key="customer_id", **params
    ).fit(X)
    print(params, small.n_features_out_)
text
{'max_relationship_depth': 1} 87
{'max_relationship_depth': 2, 'primitives': ['count', 'mean']} 67
{'max_relationship_depth': 2, 'include': ['*orders.amount*']} 21
{'max_relationship_depth': 2, 'exclude': ['*noise*']} 64
python
try:
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=2,
        max_features=20,
    ).fit(X)
except ValueError as error:
    print(error)
text
The catalog has 126 expressions, more than max_features=20. Reduce max_relationship_depth, max_lookup_depth or max_categories, pass conditional=False, or narrow it with include/exclude.

Feature names ​

Canonical names are long by design: they say exactly how a value was computed. When a downstream tool needs short identifiers, use feature_names="safe" for stable aliases. describe_expressions from sklink.inspection maps each column back to its expression.

python
safe = RelationalFeaturizer(
    db,
    entity="customers",
    key="customer_id",
    max_relationship_depth=1,
    feature_names="safe",
).fit(X)
print(safe.get_feature_names_out()[:3])
text
['f0_2eb6a5da' 'f1_1442954b' 'f2_c8e48c60']

pandas output ​

Use set_output(transform="pandas") to inspect the results with named columns.

python
featurizer.set_output(transform="pandas")
frame = featurizer.transform(X)
print(frame[["count(orders)", "mean(orders.amount)"]].head(3))
text
   count(orders)  mean(orders.amount)
0           20.0             103.4575
1            1.0             341.7300
2            4.0             189.8775

These are two columns of the fitted catalog: the number of orders of each customer and their mean amount.

Keys that are not in the entity table ​

At prediction time, X can hold a new customer that is not yet in the database. By default that is an error. With handle_unknown_entity="empty", unknown keys are treated as entities without related rows: counts are 0 and means are missing. Below, the first row is a known customer and the second is unknown; the first two columns are attributes of customers.

python
import pandas as pd

new_customers = pd.DataFrame({"customer_id": [0, 123456]})
lenient = RelationalFeaturizer(
    db,
    entity="customers",
    key="customer_id",
    max_relationship_depth=1,
    handle_unknown_entity="empty",
).fit(X)
print(lenient.transform(new_customers)[:, :4])
text
[[ 0.34620441 -0.04217825 20.          5.        ]
 [        nan         nan  0.          0.        ]]

Extra columns of X ​

Columns of X other than the key, and the time column in temporal mode, are kept as features when passthrough=True (the default). Use them for values that are not in the database, such as the result of a previous model. Set passthrough=False to drop them.

Parameters at a glance ​

ParameterDefaultWhat it does
databaseNoneThe relational data. None uses only the columns of X
entityNoneTable the samples belong to
keyNoneColumn(s) of X with the entity key, by name or position. None uses the columns named like the primary key
timeNoneColumn of X with each sample's cutoff. See time and cutoffs
max_relationship_depth2Relationships a path may follow
max_lookup_depth1Many-to-one steps from the rows of the longest paths, for conditions and aggregates
primitives"default"Aggregations to apply
conditionalTruemean and sum of numeric columns per category, for columns with at most max_categories categories
max_categories10Frequent categories per column that get their own features
max_featuresNoneFail if the catalog is larger
windowsNoneTemporal mode: also aggregate over these windows before the cutoff
include, excludeNoneGlob patterns that keep or drop expressions
allow_reverse_pathsFalseAllow paths that read other entities' rows through a shared table
passthroughTrueKeep the other columns of X
handle_unknown_entity"error""error" or "empty" for keys missing from the entity table
feature_names"canonical""canonical" names or short "safe" aliases
n_jobsNoneReserved: has no effect yet. Forests do use n_jobs

Try a relational decision tree to learn the conditions and thresholds as part of fitting the model.

Released under the MIT License.