This is the development version.
Skip to content

From your own tables to X and y ​

X has one row per prediction you want to make and holds the key of the entity, plus a cutoff date when the prediction is made at a point in time. y holds the answer for each row of X. The related tables go in the Database; the label must not be in any of them. This tutorial builds both for a churn problem, starting from two plain pandas tables.

The other tutorials use generated data where X and y are given. On your own data, deciding what one row of X is comes first, because it decides what the model predicts.

Start from your tables ​

A shop has customers and their orders, each with a date. Some customers stop ordering at some point; the goal is to predict, on a given date, which customers will place no order in the next 60 days.

The block below only simulates a shop so the page runs on its own. With your data, replace it with your own loading code, such as customers = pd.read_parquet("customers.parquet"). All you need is a customers table with one row per customer and an orders table with order_id, customer_id and a date column.

python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
start = pd.Timestamp("2024-01-01")
customers = pd.DataFrame(
    {"customer_id": np.arange(200), "plan": rng.choice(["basic", "plus"], 200)}
)
rows = []
for customer, plan in zip(customers["customer_id"], customers["plan"]):
    pace = rng.gamma(2.0, 4.0 if plan == "basic" else 6.0)  # orders per 100 days
    stops = start + pd.Timedelta(days=int(rng.integers(60, 600)))
    for day in np.sort(rng.integers(0, 365, rng.poisson(pace * 3.65))):
        created_at = start + pd.Timedelta(days=int(day))
        if created_at < stops:
            channel = rng.choice(["web", "app", "store"])
            rows.append((customer, created_at, channel, rng.gamma(2.0, 30.0)))
orders = pd.DataFrame(rows, columns=["customer_id", "created_at", "channel", "amount"])
orders.insert(0, "order_id", np.arange(len(orders)))
print(orders.shape)
print(orders.head(3).round(2))
text
(6248, 5)
   order_id  customer_id created_at channel  amount
0         0            0 2024-01-11   store   54.35
1         1            0 2024-01-15     web   81.99
2         2            0 2024-02-24     app  127.70

Describe the tables once, with created_at as the time column of orders. This tells scikit-link which orders exist at each date.

python
from sklink import Database

db = Database(
    tables={"customers": customers, "orders": orders},
    primary_keys={"customers": "customer_id", "orders": "order_id"},
    relationships=[("orders.customer_id", "customers.customer_id")],
    time_columns={"orders": "created_at"},
)

Choose what one row of X is ​

One row of X is one prediction: here, one customer on one date. Predicting for every customer on the first day of each month from April to October gives seven rows per customer. Each row carries the customer key and its cutoff, the date the prediction is made.

python
cutoffs = pd.date_range("2024-04-01", "2024-10-01", freq="MS")
X = customers[["customer_id"]].merge(pd.DataFrame({"cutoff": cutoffs}), how="cross")
print(X.shape)
print(X.head(3))
text
(1400, 2)
   customer_id     cutoff
0            0 2024-04-01
1            0 2024-05-01
2            0 2024-06-01

Once you pass time="cutoff" to the estimator, as below, the model sees at each cutoff only the orders created before it. A customer can appear many times in X, once per cutoff, and the same customer with a later cutoff sees more orders.

Compute the label from what happens next ​

y is computed by you, from the data after each cutoff: a customer churns at a cutoff when they place no order in the following 60 days. This window after the cutoff is the label horizon.

python
horizon = pd.Timedelta(days=60)
pairs = X.merge(orders[["customer_id", "created_at"]], on="customer_id")
ordered = pairs[
    (pairs["created_at"] >= pairs["cutoff"])
    & (pairs["created_at"] < pairs["cutoff"] + horizon)
]
active = pd.MultiIndex.from_frame(ordered[["customer_id", "cutoff"]])
y = (~pd.MultiIndex.from_frame(X).isin(active)).astype(int)
print(f"{y.mean():.2f} of the rows churn")
text
0.24 of the rows churn

The code pairs each row of X with that customer's orders, keeps the orders that fall in the 60 days from the cutoff, and sets the label to 1 when a customer and cutoff pair has none.

The label reads the future on purpose; the features must not. scikit-link takes care of the features: with time="cutoff", an order at or after the cutoff never reaches a feature or a split.

Validate on later dates ​

A random split would train on October and test on May. TemporalCutoffSplit trains on earlier cutoffs and tests on later ones. With label_horizon="60D", it also leaves out training rows whose 60-day window overlaps the test dates, since their labels were not known yet.

python
from sklearn.model_selection import cross_val_score
from sklink.ensemble import RelationalRandomForestClassifier
from sklink.model_selection import TemporalCutoffSplit

cv = TemporalCutoffSplit(time="cutoff", n_splits=3, label_horizon="60D")
forest = RelationalRandomForestClassifier(
    db,
    entity="customers",
    key="customer_id",
    time="cutoff",
    n_estimators=50,
    random_state=0,
)
scores = cross_val_score(forest, X, y, cv=cv, scoring="roc_auc")
print(scores.round(2))
text
[0.9  0.87 0.9 ]

Read what the model learned ​

A shallow tree on the same rows shows the questions that matter. With a time column, scikit-link adds time-based aggregates such as time_since_last, the number of days between the last order and the cutoff.

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

tree = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", time="cutoff", max_depth=2
).fit(X, y)
print(export_text(tree))
text
|--- time_since_last(orders.created_at) <= 33.500
|   |--- time_since_last(orders.created_at) <= 19.500
|   |   |--- class: 0
|   |--- time_since_last(orders.created_at) >  19.500
|   |   |--- class: 0
|--- time_since_last(orders.created_at) >  33.500
|   |--- time_since_last(orders.created_at) <= 87.500
|   |   |--- class: 1
|   |--- time_since_last(orders.created_at) >  87.500
|   |   |--- class: 1

The tree predicts churn for customers whose last order is more than about a month old at the cutoff. The second-level splits change the predicted probability, not the class. That matches how the data was made: churners stop ordering.

When there is no date ​

When the label does not depend on a date, such as a customer's segment known from another system, X is just the key column and y is that label, in the same order:

python
labels = pd.DataFrame(
    {"customer_id": customers["customer_id"], "segment": rng.integers(0, 2, 200)}
)
X_static = labels[["customer_id"]]
y_static = labels["segment"].to_numpy()
print(X_static.shape, y_static.shape)
text
(200, 1) (200,)

If your customers table had a label column, say churned, take it out of the table before building the Database, or list it in Database(..., exclude={"customers": ["churned"]}). Otherwise the model reads the answer. The same goes for any column filled in only after the outcome, such as a cancellation reason.

Checklist ​

  • One row of X per prediction, with the key of the entity table and, for predictions at a date, a cutoff column.
  • y in the same order as X, computed from what happens after each cutoff, over a fixed label horizon.
  • No label in the database: drop it, or use exclude.
  • time= on the estimator when X has cutoffs, and a time column on every table whose rows have a date.
  • Validate by date with TemporalCutoffSplit and label_horizon.

Next: time and cutoffs covers windows such as the last 30 days, and model selection covers tuning.

Released under the MIT License.