Skip to content

Custom primitives and expressions ​

To add an aggregation, implement a NumPy kernel and register it with a Primitive that describes its inputs and output. You can then request it in RelationalFeaturizer by name. Here spread measures the difference between a customer's largest and smallest order amounts.

The built-in primitives ​

python
from sklink.primitives import default_primitives, list_primitives

print(list_primitives())
print("numeric columns get", default_primitives("numeric"))
print("categorical columns get", default_primitives("categorical"))
text
['all', 'any', 'count', 'entropy', 'exists', 'first', 'last', 'max', 'mean', 'median', 'min', 'mode', 'nunique', 'proportion', 'quantile', 'std', 'sum', 'time_since_first', 'time_since_last', 'trend']
numeric columns get ('sum', 'mean', 'min', 'max', 'std', 'last', 'trend')
categorical columns get ('nunique', 'mode')

list_primitives() shows what's available. default_primitives() shows what the featurizer chooses for a semantic type; last and trend apply only in temporal mode, on tables with a time column. To use an optional aggregation such as median, name it in the primitives list.

Write a kernel ​

A kernel gets the rows that matched the expression's path, visibility rules and conditions. It returns one result per group. Samples that refer to the same entity share a group in static mode. In temporal mode, they also need the same cutoff.

  • group gives the group index of each input row, in group order.
  • values contains the column values as float64. Rows with a missing value in that column have already been removed from both arrays.
  • n gives the total group count, including groups with no matching rows.
  • params and ctx supply primitive parameters and context. In temporal mode, ctx.cutoff_seconds holds each group's cutoff in seconds since the epoch, and a primitive registered with requires_time=True also gets ctx.row_seconds, the time of each row, as last and trend do; such a primitive is only offered on tables with a time column. spread needs neither.

Return an array of values and a Boolean mask of missing results, both of length n. A group with one order has spread zero. A group with no order amounts has a missing result.

python
import numpy as np


def spread_kernel(group, values, n, params, ctx):
    low = np.full(n, np.inf)
    high = np.full(n, -np.inf)
    np.minimum.at(low, group, values)
    np.maximum.at(high, group, values)
    missing = np.bincount(group, minlength=n) == 0
    result = np.where(missing, np.nan, high - low)
    return result, missing

Register the primitive ​

python
from sklink.primitives import Primitive, register_primitive

register_primitive(
    Primitive(
        name="spread",
        input_types=frozenset({"numeric"}),
        output_type="numeric",
        empty_value="missing",
        decomposable=False,
    ),
    backends={"numpy": spread_kernel},
)
print("spread" in list_primitives())
text
True
Primitive fieldMeaning
nameLowercase identifier used in canonical names
input_typesSemantic types it accepts, or {"rows"} for row counts
output_typeSemantic type of the result, or "same"
empty_valueResult without rows: "zero", "false" or "missing"
decomposableComputable from running sums; only those take learned conditions in trees
requires_timeNeeds temporal mode and a time column on the aggregated table; the kernel gets ctx.row_seconds
paramsNames of its parameters, such as ("q",) for quantile
needs_whereMeaningless without a condition, like proportion

A "numpy" kernel is required: it is the reference every backend can fall back on.

Use it on order amounts ​

Load the bundled shop dataset and request spread in the featurizer's primitive list. The last output column is the range of order amounts. Besides count and spread, the catalog keeps the customers' own columns and the per-category counts and proportions of type.

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

shop = load_shop()
featurizer = RelationalFeaturizer(
    shop.database,
    entity="customers",
    key="customer_id",
    max_relationship_depth=1,
    primitives=["count", "spread"],
)
features = featurizer.fit_transform(shop.X)
print(featurizer.get_feature_names_out())
print(features[:3, -1])
text
['region' 'segment' 'count(orders)' "count(orders[type == 'express'])"
 "count(orders[type == 'pickup'])" "count(orders[type == 'standard'])"
 "proportion(orders[type == 'express'])"
 "proportion(orders[type == 'pickup'])"
 "proportion(orders[type == 'standard'])" 'spread(orders.amount)']
[116.94  78.03 117.62]

The last column is the difference between each customer's largest and smallest order amounts. Check get_feature_names_out() to see which expression produced each column.

Share it as a plugin ​

To make a primitive available to other projects, put your registration code in a function and expose it in the sklink.primitives entry point group. When scikit-link first looks up available primitives, it calls the function provided by the installed plugin.

toml
[project.entry-points."sklink.primitives"]
my_primitives = "my_package.primitives:register"

Read and build expressions ​

Use parse to turn a feature name into an expression checked against the database schema. Start from the same entity used by the estimator. You can format the expression back to its name or inspect its parts in the dictionary returned by to_dict().

python
from sklink.expressions import format_expression, parse

expression = parse(
    "mean(orders.amount[type == 'express'])", shop.database.schema, entity="customers"
)
print(type(expression).__name__)
print(format_expression(expression))
print(expression.to_dict()["where"])
text
Aggregate
mean(orders.amount[type == 'express'])
[{'column': 'type', 'op': '==', 'value': 'express'}]

Use the column names in the schema when you write an expression. This example asks for price in orders, where the column is called amount. The parser reports which table and column it could not find.

python
from sklink.exceptions import SchemaError

try:
    parse("mean(orders.price)", shop.database.schema, entity="customers")
except SchemaError as error:
    print(error)
text
Table 'orders' has no column 'price'.

The API reference documents the expression classes (Aggregate, Attribute, Condition, Path, Window) and helpers such as enumerate_expressions.

Released under the MIT License.