Skip to content

8 relational feature recipes for Python ​

Use RelationalFeaturizer to count orders per customer, aggregate amounts by order type and follow order items to products. Use load_shop() to run the examples in the same session. names() fits a featurizer and lists the columns it would return from transform for the customers in X.

python
from sklink.datasets import load_shop
from sklink.feature_extraction import RelationalFeaturizer

shop = load_shop()
db, X = shop.database, shop.X


def names(**params):
    featurizer = RelationalFeaturizer(
        db, entity="customers", key="customer_id", **params
    )
    return list(featurizer.fit(X).get_feature_names_out())
python
order_counts = [
    name
    for name in names(max_relationship_depth=1, primitives=["count"])
    if name == "count(orders)" or name.startswith("count(orders[")
]
print(order_counts[:3])
text
['count(orders)', "count(orders[type == 'express'])", "count(orders[type == 'pickup'])"]

count(orders) counts all orders for a customer. The names with brackets count orders of one type. This prints the first three matching columns.

2. Aggregate a numeric column per category ​

python
for name in names(max_relationship_depth=1):
    if name.startswith("mean(orders.amount["):
        print(name)
text
mean(orders.amount[type == 'express'])
mean(orders.amount[type == 'pickup'])
mean(orders.amount[type == 'standard'])

3. Reach tables several relationships away ​

Products are three relationships away from customers: through orders and order items. At the default depth of 2, a lookup of each order line's product already reads some of their columns, such as mean(orders.order_items.products.price); depth 3 makes products part of the path.

python
deep = [name for name in names(max_relationship_depth=3) if ".products" in name]
print(len(deep), "features reach products, for example:")
print(deep[0])
print(deep[-1])
text
23 features reach products, for example:
count(orders.order_items.products[category == 'books'])
sum(orders.order_items.products.price[category == 'kitchen'])

4. Keep only some tables or columns ​

Pass include glob patterns to keep matching expression names, table names or relationship names. This example keeps aggregations of product prices.

python
print("\n".join(names(max_relationship_depth=3, include=["*products.price*"])))
text
max(orders.order_items.products.price)
mean(orders.order_items.products.price)
mean(orders.order_items.products.price[category == 'books'])
mean(orders.order_items.products.price[category == 'games'])
mean(orders.order_items.products.price[category == 'garden'])
mean(orders.order_items.products.price[category == 'kitchen'])
min(orders.order_items.products.price)
std(orders.order_items.products.price)
sum(orders.order_items.products.price)
sum(orders.order_items.products.price[category == 'books'])
sum(orders.order_items.products.price[category == 'games'])
sum(orders.order_items.products.price[category == 'garden'])
sum(orders.order_items.products.price[category == 'kitchen'])

5. Limit the aggregation functions ​

python
print(len(names()), "default features")
print(len(names(primitives=["count", "sum"])), "with count and sum")
text
54 default features
28 with count and sum

Frequent categories still get their count and proportion columns, and conditional aggregates use only sum here, since mean is not in the list.

6. Set a limit on the number of features ​

max_features raises an error if the number of generated expressions exceeds the limit. Narrow the paths, categories or expression names and fit again.

python
try:
    names(max_features=50)
except ValueError as error:
    print(error)
text
The catalog has 54 expressions, more than max_features=50. Reduce max_relationship_depth, max_lookup_depth or max_categories, pass conditional=False, or narrow it with include/exclude.

7. Short names for downstream tools ​

python
print(names(max_relationship_depth=1, feature_names="safe")[:3])
text
['f0_1171b3d5', 'f1_b3166a4d', 'f2_c8e48c60']

The output names and sklink.inspection.describe_expressions(featurizer) are in the same order. Use that order to look up what an alias computes.

8. Let a tree pick the features ​

Fit a relational tree when you want the labels to guide which aggregations become splits. This tree classifies a customer by whether they placed at least three orders.

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, shop.y)))
text
|--- count(orders) <= 2.500
|   |--- class: 0
|--- count(orders) >  2.500
|   |--- class: 1

Further reading on relational features ​

Released under the MIT License.