Skip to content

Quickstart ​

Predict one label per customer from their orders. First, turn the order history into columns for a scikit-learn classifier. Then fit a relational tree and trace one customer's prediction.

The shop is a small teaching dataset. Its label is defined in advance: a customer with at least three orders has label 1, and all others have label 0. This lets you check a learned rule against the order records. Run the blocks in order after installing scikit-link with pandas.

To run a similar example in the browser without installing anything, open the quickstart notebook in Colab.

1. Load a relational database ​

load_shop reads four tables included in the package. Start at customers and follow customer_id to find a customer's orders. To find the products in one order, follow order_id to its line items, then product_id to the catalog. The forked end of each link marks the side where a key can occur many times.

Shop schema. One customer has many orders, an order has many line items, and each line item refers to one product.

python
from sklink.datasets import load_shop

shop = load_shop(output="pandas")
for table in shop.database.table_names:
    print(table, shop.database.n_rows(table))
print(shop.X.head(3))
print(shop.y[:3])
text
customers 24
orders 56
order_items 119
products 12
   customer_id
0            1
1            2
2            3
[1 1 1]

Keep the roles of these three objects separate when using your own data:

  • shop.database holds the tables and how their keys link them.
  • shop.X has one row per sample, that is, per prediction: here one row per customer, with the key customer_id. It is the table you would pass to any scikit-learn model. The table whose rows you predict for, customers, is the entity table, and entity="customers" names it.
  • shop.y holds one label for each row of shop.X, in the same order. The first three customers shown above all have label 1.

RelationalFeaturizer is a scikit-learn transformer. Given the database, the entity table and the key column of X, it computes aggregates of the related rows for every sample.

python
from sklink.feature_extraction import RelationalFeaturizer

featurizer = RelationalFeaturizer(shop.database, entity="customers", key="customer_id")
features = featurizer.fit_transform(shop.X)
print(features.shape)
print(featurizer.get_feature_names_out()[:6])
text
(24, 54)
['region' 'segment' 'count(orders)' "count(orders[type == 'express'])"
 "count(orders[type == 'pickup'])" "count(orders[type == 'standard'])"]

The result has one row per customer and one column per feature. region and segment are columns of the customers table itself, used as they are. For example, count(orders[type == 'express']) counts just that customer's express orders. However many orders a customer has, they keep exactly one row: their orders are summarized into these columns.

3. Use it in a pipeline ​

Pass the original shop.X to cross-validation, not the features matrix from step 2. The featurizer learns things during fit, such as which order types exist. If it learns them from all customers, the test folds help shape the features and the score is too optimistic. Inside a pipeline, each fold fits the featurizer on its training customers only.

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

pipe = make_pipeline(
    RelationalFeaturizer(shop.database, entity="customers", key="customer_id"),
    HistGradientBoostingClassifier(max_iter=50, min_samples_leaf=3, random_state=0),
)
scores = cross_val_score(pipe, shop.X, shop.y, cv=3)
print(f"accuracy: {scores.mean():.2f}")
text
accuracy: 0.96

4. Let a decision tree read the tables ​

The pipeline scored 0.96 mean accuracy over three folds on these 24 customers. To see which order rule the data supports, fit a separate relational tree on all 24 customers and print its splits.

python
from sklink.inspection import export_text
from sklink.tree import RelationalDecisionTreeClassifier

tree = RelationalDecisionTreeClassifier(
    shop.database, entity="customers", key="customer_id", max_depth=2, random_state=0
)
tree.fit(shop.X, shop.y)
print(export_text(tree))
text
|--- count(orders) <= 2.500
|   |--- class: 0
|--- count(orders) >  2.500
|   |--- class: 1

An order count is a whole number, so > 2.500 means at least three orders. Customer 1 placed five orders. Follow the highlighted branch to class 1 and check that prediction with the fitted estimator.

Fitted shop tree. The first customer follows the branch above 2.5 orders to class 1.

python
from sklink.plotting import TreeDisplay

customer = shop.X.iloc[:1]
print(tree.predict(customer).item())
TreeDisplay.from_estimator(tree, customer).save("shop-tree.svg")
text
1

The SVG records the fitted split and the selected path. To explore the nodes in a notebook, display TreeDisplay.from_estimator(tree, customer) in a cell.

Next steps ​

Released under the MIT License.