---
url: /dev/case-studies/subscription-churn.md
description: >-
  An end-to-end churn model on related tables: build the database, label each
  account at monthly cutoffs, compare models by date, explain one account and
  deploy.
---

# Case study: churn from usage and support tickets

**This case study goes from raw tables to a deployed model: a subscription
app wants to know, on the first day of each month, which active accounts will
not open the app in the next 60 days. Sessions and support tickets live in
their own tables, so every prediction reads the related rows of one account
as of one date.** It combines what the tutorials show one at a time:
[your own `X` and `y`](../tutorials/your-own-data),
[time and cutoffs](../tutorials/time-and-cutoffs),
[relational features](../tutorials/relational-features),
[gradient boosting](../tutorials/relational-gradient-boosting),
[inspection](../tutorials/inspect-and-explain) and
[deployment](../tutorials/save-and-deploy).

## The tables

The app has a `plans` table, an `accounts` table, a `sessions` table with one
row each time an account opens the app, and a `tickets` table with support
requests. Accounts that are about to leave use the app less and open billing
or bug tickets that stay unresolved; some loyal accounts also take breaks of
a few weeks, so a quiet month alone does not mean churn.

```python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
start = pd.Timestamp("2024-01-01")
n = 500
plans = pd.DataFrame(
    {"plan_id": [0, 1, 2], "name": ["basic", "plus", "pro"], "price": [9.0, 19.0, 49.0]}
)
accounts = pd.DataFrame(
    {
        "account_id": np.arange(n),
        "plan_id": rng.choice(3, n, p=[0.5, 0.35, 0.15]),
        "country": rng.choice(["CO", "MX", "US", "ES"], n),
    }
)
sessions, tickets = [], []
for account, plan in zip(accounts["account_id"], accounts["plan_id"]):
    rate = rng.gamma(2.0, 0.15 + 0.1 * plan)  # sessions per day
    stops = int(rng.integers(90, 700))  # the day the account leaves
    breaks = set()
    for _ in range(rng.poisson(1.5)):  # holidays without sessions
        first = int(rng.integers(0, 366))
        breaks.update(range(first, first + int(rng.integers(10, 45))))
    for day in range(min(stops, 366)):  # 2024 has 366 days
        leaving = day >= stops - 60
        usage = 0.0 if day in breaks else (0.5 if leaving else 1.0)
        for _ in range(rng.poisson(rate * usage)):
            minute = int(rng.integers(0, 1440))
            sessions.append(
                (
                    account,
                    start + pd.Timedelta(days=day, minutes=minute),
                    rng.choice(["web", "ios", "android"]),
                    rng.gamma(2.0, 6.0),
                )
            )
        if rng.random() < 0.004 + (0.03 if leaving else 0.0):
            topics = [0.45, 0.4, 0.15] if leaving else [0.2, 0.3, 0.5]
            tickets.append(
                (
                    account,
                    start + pd.Timedelta(days=day),
                    rng.choice(["billing", "bug", "how-to"], p=topics),
                    bool(rng.random() < (0.4 if leaving else 0.9)),
                )
            )
sessions = pd.DataFrame(
    sessions, columns=["account_id", "started_at", "device", "minutes"]
)
sessions.insert(0, "session_id", np.arange(len(sessions)))
tickets = pd.DataFrame(
    tickets, columns=["account_id", "opened_at", "topic", "resolved"]
)
tickets.insert(0, "ticket_id", np.arange(len(tickets)))
print(sessions.shape, tickets.shape)
```

```text
(62180, 5) (1035, 5)
```

## Describe the database

Each table gets its key, each foreign key a relationship, and each event
table its time column, so that scikit-link knows which rows exist at each
date. `plans` is a parent of `accounts`: a model can read the price of an
account's plan through it.

```python
from sklink import Database

db = Database(
    tables={
        "plans": plans,
        "accounts": accounts,
        "sessions": sessions,
        "tickets": tickets,
    },
    primary_keys={
        "plans": "plan_id",
        "accounts": "account_id",
        "sessions": "session_id",
        "tickets": "ticket_id",
    },
    relationships=[
        ("accounts.plan_id", "plans.plan_id"),
        ("sessions.account_id", "accounts.account_id"),
        ("tickets.account_id", "accounts.account_id"),
    ],
    time_columns={"sessions": "started_at", "tickets": "opened_at"},
)
print(
    {table: db.n_rows(table) for table in ["plans", "accounts", "sessions", "tickets"]}
)
```

```text
{'plans': 3, 'accounts': 500, 'sessions': 62180, 'tickets': 1035}
```

## One row per account and month

A prediction is made for an account on the first day of a month, so `X` has
one row per account and cutoff. Only accounts with a session in the 60 days
before the cutoff are still active and worth scoring; breaks are shorter
than that, so loyal accounts on holiday stay in. The label reads the 60 days
after the cutoff: `1` when the account opens no session in that window.

```python
cutoffs = pd.date_range("2024-04-01", "2024-11-01", freq="MS")
X = accounts[["account_id"]].merge(pd.DataFrame({"cutoff": cutoffs}), how="cross")
pairs = X.merge(sessions[["account_id", "started_at"]], on="account_id")
before = pairs[
    (pairs["started_at"] < pairs["cutoff"])
    & (pairs["started_at"] >= pairs["cutoff"] - pd.Timedelta(days=60))
]
after = pairs[
    (pairs["started_at"] >= pairs["cutoff"])
    & (pairs["started_at"] < pairs["cutoff"] + pd.Timedelta(days=60))
]
rows = pd.MultiIndex.from_frame(X)
X = X[rows.isin(pd.MultiIndex.from_frame(before[["account_id", "cutoff"]]))]
X = X.reset_index(drop=True)
active = pd.MultiIndex.from_frame(after[["account_id", "cutoff"]])
y = (~pd.MultiIndex.from_frame(X).isin(active)).astype(int)
print(X.shape, f"{y.mean():.2f} churn")
```

```text
(3593, 2) 0.09 churn
```

## Keep the last months for the final test

Model choices are made with temporal cross-validation on the cutoffs up to
August. The October and November cutoffs are kept aside to measure the
chosen model once, as it would run in production. September is left out
because its 60-day labels overlap October.

```python
from sklink.model_selection import TemporalCutoffSplit

train = (X["cutoff"] < "2024-09-01").to_numpy()
test = (X["cutoff"] >= "2024-10-01").to_numpy()
cv = TemporalCutoffSplit(time="cutoff", n_splits=3, label_horizon="60D")
common = {"entity": "accounts", "key": "account_id", "time": "cutoff"}
print(train.sum(), test.sum())
```

```text
2395 776
```

## Search the features of a pipeline

A `RelationalFeaturizer` in front of scikit-learn's
`HistGradientBoostingClassifier` is the first candidate. Its parameters are
searched like any other step's: here, whether aggregates over the last 30 or
90 days help besides the whole history. Average precision measures how well
the model ranks the accounts that churn, which matters more than accuracy
when a team can only call a few of them.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklink.feature_extraction import RelationalFeaturizer

pipe = make_pipeline(
    RelationalFeaturizer(db, **common),
    HistGradientBoostingClassifier(random_state=0),
)
search = GridSearchCV(
    pipe,
    {"relationalfeaturizer__windows": [None, ["30D"], ["30D", "90D"]]},
    cv=cv,
    scoring="average_precision",
).fit(X[train], y[train])
print(search.best_params_, f"{search.best_score_:.3f}")
```

```text
{'relationalfeaturizer__windows': ['30D', '90D']} 0.523
```

## A relational model with the same folds

`RelationalGradientBoostingClassifier` learns its aggregates and their
conditions while it fits, such as whether all of an account's tickets were
resolved, instead of choosing from a fixed catalog. It goes through the same
folds and metric.

```python
from sklearn.model_selection import cross_val_score
from sklink.ensemble import RelationalGradientBoostingClassifier

boosting = RelationalGradientBoostingClassifier(db, random_state=0, **common)
scores = cross_val_score(
    boosting, X[train], y[train], cv=cv, scoring="average_precision"
)
print(f"{scores.mean():.3f}")
```

```text
0.431
```

The pipeline ranks better in these folds. The relational model is still
carried through the rest of this study, because it explains itself as
conditions on sessions and tickets, a trade a team can weigh against the
score; the pipeline goes through the same deployment steps. The last months
only report how both do.

## Score both candidates once on the last months

Both candidates are refit on all training cutoffs and scored on October and
November. Besides average precision, the share of churners among the 100
accounts with the highest risk says how useful a call list of that size
would be.

```python
from sklearn.metrics import average_precision_score

boosting.fit(X[train], y[train])
for name, model in [
    ("featurizer + HGB", search.best_estimator_),
    ("relational GB", boosting),
]:
    risk = model.predict_proba(X[test])[:, 1]
    top = np.argsort(-risk)[:100]
    print(
        f"{name:<17} AP {average_precision_score(y[test], risk):.3f}"
        f"  churners in top 100 {y[test][top].mean():.2f}"
    )
```

```text
featurizer + HGB  AP 0.730  churners in top 100 0.64
relational GB     AP 0.701  churners in top 100 0.62
```

## Explain the model and one account

`aggregate_importances` says which tables and expressions the boosted model
relies on; `explain` lists the expressions the model consulted most for one
account, with their values at that account's cutoff. `time_since_*` values
are in days.

```python
from sklink.inspection import aggregate_importances, explain

by_table = aggregate_importances(boosting, by="table")
print({table: round(share, 2) for table, share in by_table.items()})
for expression, share in list(aggregate_importances(boosting).items())[:4]:
    print(f"{share:.2f} {expression}")

account = explain(boosting, X[test].iloc[:1])[0]
print("churn probability", round(account["value"][1], 3))
for item in account["contributions"][:3]:
    print(f"  {item['expression']} = {item['value']:.1f}")
```

```text
{'sessions': 0.71, 'tickets': 0.29, 'accounts': 0.0, 'plans': 0.0}
0.33 time_since_last(sessions.started_at)
0.12 all(tickets.resolved)
0.05 time_since_last(tickets.opened_at)
0.05 time_since_first(sessions.started_at)
churn probability 0.459
  time_since_last(sessions.started_at) = 3.8
  time_since_last(tickets.opened_at) = 34.0
  time_since_first(sessions.started_at) = 270.3
```

## Deploy and score next month

Before saving, `sklink.detach` drops the tables from the fitted model, so the
file holds only what it learned. Both calls take a pipeline too. In production, `sklink.rebind` attaches the
current tables, and the model scores the accounts active in the 60 days
before the first of December, as of that date.

```python
import pickle

import sklink

blob = pickle.dumps(sklink.detach(boosting))
production = sklink.rebind(pickle.loads(blob), db)
november = sessions["started_at"].between("2024-10-02", "2024-12-01", inclusive="left")
recent = sessions.loc[november, "account_id"].unique()
december = pd.DataFrame({"account_id": recent, "cutoff": pd.Timestamp("2024-12-01")})
risk = production.predict_proba(december)[:, 1]
print(
    f"{len(blob) / 1e6:.1f} MB;",
    (risk > 0.5).sum(),
    "of",
    len(december),
    "active accounts at risk",
)
```

```text
0.4 MB; 32 of 350 active accounts at risk
```

## What to take from it

* **The cutoff does the leakage work.** With `time="cutoff"`, every feature,
  split and explanation only sees sessions and tickets from before the
  prediction date, and `TemporalCutoffSplit` with `label_horizon` keeps the
  validation honest.
* **Featurizer and relational model are both scikit-learn estimators.** They
  go through the same `GridSearchCV`, `cross_val_score` and metrics, so the
  comparison is fair and the choice is yours.
* **A held-out period answers the business question.** Cross-validation
  compares the candidates; the last months say how well a call list would
  work.

Next: [tune the models](../guides/tuning).
