Case study: segment accounts and flag unusual ones
A bank has accounts, their card transactions and the merchants behind them, but no labels: nobody has tagged the customer types or the suspicious accounts. A relational clustering tree splits the accounts into segments that each read as a rule on their transactions. A relational isolation forest ranks the accounts whose transactions look unlike anyone else's. Both learn from the related rows directly, so no feature table is built by hand. See the clustering and anomaly detection tutorials for each model on its own.
The tables
Accounts behave in three ways: commuters make many small transport payments, families shop for groceries and electronics, and travellers pay hotels and airlines abroad. Eight accounts also send a few very large payments to crypto and jewelry merchants. The generator keeps the true type and the eight accounts aside, to check the results at the end; the models never see them.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
start = pd.Timestamp("2024-01-01")
merchants = pd.DataFrame(
{
"merchant_id": np.arange(12),
"category": ["transport"] * 3
+ ["groceries"] * 3
+ ["travel"] * 3
+ ["electronics", "crypto", "jewelry"],
"country": ["CO"] * 6 + ["US", "ES", "MX", "CO", "MT", "AE"],
}
)
profiles = { # merchants, mean amount, transactions per month
"commuter": ([0, 1, 2, 3], 4.0, 20),
"family": ([3, 4, 5, 9], 60.0, 20),
"traveller": ([6, 7, 8, 3], 250.0, 20),
}
n = 400
kind = rng.choice(list(profiles), n, p=[0.45, 0.4, 0.15])
unusual = rng.choice(n, 8, replace=False)
accounts = pd.DataFrame(
{"account_id": np.arange(n), "opened_year": rng.integers(2010, 2024, n)}
)
rows = []
for account, k in zip(range(n), kind):
shops, mean, per_month = profiles[k]
for _ in range(rng.poisson(rng.gamma(4.0, per_month / 4) * 6)):
minute = int(rng.integers(0, 182 * 1440))
rows.append(
(
account,
start + pd.Timedelta(minutes=minute),
int(rng.choice(shops)),
rng.gamma(2.0, mean / 2),
)
)
if account in unusual:
for _ in range(rng.integers(6, 12)):
minute = int(rng.integers(0, 182 * 1440))
rows.append(
(
account,
start + pd.Timedelta(minutes=minute),
int(rng.choice([10, 11])),
rng.gamma(4.0, 900.0),
)
)
transactions = pd.DataFrame(
rows, columns=["account_id", "made_at", "merchant_id", "amount"]
)
transactions.insert(0, "transaction_id", np.arange(len(transactions)))
print(transactions.shape)(47838, 5)A transaction points to its account and to its merchant, so the models can also read a merchant's category and country through it.
from sklink import Database
db = Database(
tables={"merchants": merchants, "accounts": accounts, "transactions": transactions},
primary_keys={
"merchants": "merchant_id",
"accounts": "account_id",
"transactions": "transaction_id",
},
relationships=[
("transactions.account_id", "accounts.account_id"),
("transactions.merchant_id", "merchants.merchant_id"),
],
)
X = accounts[["account_id"]]
common = {"entity": "accounts", "key": "account_id"}Segments that read as rules
RelationalClusteringTree grows a tree whose splits make each segment as tight as possible on the standardized aggregates of its transactions, the same objective k-means minimizes. With three segments and at least 20 accounts in each, the whole segmentation fits in a few lines:
from sklink.cluster import RelationalClusteringTree
from sklink.inspection import export_text
tree = RelationalClusteringTree(db, n_clusters=3, min_samples_leaf=20, **common).fit(X)
print(export_text(tree, decimals=1))
print("sizes:", np.bincount(tree.labels_).tolist())|--- count(transactions[amount > 192.45]) <= 7.5
| |--- max(transactions.amount) <= 71.1
| | |--- cluster: 0
| |--- max(transactions.amount) > 71.1
| | |--- cluster: 1
|--- count(transactions[amount > 192.45]) > 7.5
| |--- cluster: 2
sizes: [159, 161, 80]Each segment is a rule a person can check and act on, such as "at most a few large payments and no payment above a modest amount".
How it compares with k-means
RelationalKMeans runs k-means on aggregates of the same transactions. Its clusters have no rules, so a comparison needs a reference. The generator's true types serve here, through scikit-learn's adjusted Rand index: 1 means the same grouping, 0 a random one.
from sklearn.metrics import adjusted_rand_score
from sklink.cluster import RelationalKMeans
kmeans = RelationalKMeans(db, n_clusters=3, n_init=5, random_state=0, **common).fit(X)
print(f"clustering tree {adjusted_rand_score(kind, tree.labels_):.2f}")
print(f"k-means {adjusted_rand_score(kind, kmeans.labels_):.2f}")clustering tree 0.96
k-means 0.38Both models minimize the k-means objective on standardized aggregates, so the gap comes from what each can use. The tree's splits search learned conditions such as the number of payments above an amount, while RelationalKMeans uses plain aggregates by default (conditional=False) and weighs all of them equally, including those that vary a lot but say little about the type. The tree also builds its segments greedily, one split on one aggregate at a time, which is what makes them read as rules.
Accounts to review
RelationalIsolationForest isolates accounts with random questions about their transactions; the ones isolated in few questions get the lowest score_samples. The ten lowest form a review list:
from sklink.ensemble import RelationalIsolationForest
forest = RelationalIsolationForest(db, random_state=0, **common).fit(X)
review = np.argsort(forest.score_samples(X))[:10]
print(
"planted accounts in the review list:",
np.isin(review, unusual).sum(),
"of",
len(unusual),
)
largest = transactions[transactions["account_id"].isin(review)].nlargest(3, "amount")
print(
largest.merge(merchants, on="merchant_id")[
["account_id", "category", "country", "amount"]
].round(0)
)planted accounts in the review list: 8 of 8
account_id category country amount
0 371 crypto MT 11104.0
1 37 jewelry AE 9653.0
2 1 crypto MT 8912.0The largest payments of the listed accounts go to the crypto and jewelry merchants abroad, which is what an analyst would open the case for.
What to take from it
- Unsupervised models read related tables too. The clustering tree, k-means and the isolation forest take the same
Databaseas the supervised models, and the sametime=cutoffs when the data is dated. - Rules make segments usable. A segment defined by a rule on transactions can be explained to a business team and applied to a new account without the model.
- Rank, then review. The isolation forest gives a ranking, not a verdict; a short list for people to check is its natural output.