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.
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])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.databaseholds the tables and how their keys link them.shop.Xhas one row per sample, that is, per prediction: here one row per customer, with the keycustomer_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, andentity="customers"names it.shop.yholds one label for each row ofshop.X, in the same order. The first three customers shown above all have label1.
2. Turn the related tables into features
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.
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])(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.
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}")accuracy: 0.964. 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.
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))|--- count(orders) <= 2.500
| |--- class: 0
|--- count(orders) > 2.500
| |--- class: 1An 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.
from sklink.plotting import TreeDisplay
customer = shop.X.iloc[:1]
print(tree.predict(customer).item())
TreeDisplay.from_estimator(tree, customer).save("shop-tree.svg")1The 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
- Core concepts explains the database, the entity, the key and canonical names.
- Describe your own database starts the tutorials with your tables.
- From your own tables to X and y shows how to build one row per prediction and a label without leakage.
- Plot a model draws the schema, the tree and one prediction.
- The cookbook has short recipes for common tasks.
- Common errors explains each error message and its fix.