---
url: /stable/tutorials/clustering.md
description: >-
  Unsupervised segmentation of entities by their related rows, such as customers
  by their orders: relational k-means and clustering trees that read as rules.
---

# Cluster entities with related tables

**To group entities by what they do, such as customers, patients or
machines, cluster them on their related rows: here, how many orders each
customer places, how much they spend, which categories they buy.
`RelationalKMeans` runs k-means on those aggregates.
`RelationalClusteringTree` finds clusters that each have a short definition,
such as `count(orders) > 2.5`.** Neither needs a label.

## Customers without labels

The generator below also returns a label, which this tutorial ignores. Each
row of `X` is one customer; their orders and order items are in `db`.

```python
from sklink.datasets import make_relational_classification

db, X, _ = make_relational_classification(
    n_entities=600, signal="mixed", random_state=0
)
print(X.columns.tolist())
```

```text
['customer_id']
```

## K-means on relational features

`RelationalKMeans` describes each customer with the features of
[`RelationalFeaturizer`](./relational-features), without conditional
aggregates (`conditional=False`, the default here), standardizes them (a
category becomes one indicator per value, and a missing value, such as the
mean amount of a customer without orders, the average) and runs
scikit-learn's `KMeans` on the result.

```python
import numpy as np
from sklink.cluster import RelationalKMeans

kmeans = RelationalKMeans(
    db, entity="customers", key="customer_id", n_clusters=4, n_init=5, random_state=0
).fit(X)
print("sizes:", np.bincount(kmeans.labels_).tolist())
print(len(kmeans.embedding_feature_names_), "standardized features")
```

```text
sizes: [160, 111, 184, 145]
79 standardized features
```

`cluster_centers_` holds the centers in that standardized space, one column
per name of `embedding_feature_names_`. A large positive value means the
cluster is above average on that feature:

```python
center = kmeans.cluster_centers_[0]
for i in np.argsort(-np.abs(center))[:3]:
    print(f"{center[i]:+.2f}  {kmeans.embedding_feature_names_[i]}")
```

```text
+1.28  count(orders[type == 'economy'])
+1.23  count(orders[type == 'standard'])
+0.92  count(orders.order_items)
```

`predict` assigns new customers to the closest center and `transform` gives
their distance to every center, which other models can use as features.

Every standardized feature has the same weight. A table with many columns
therefore has more say than a table with few. Select features with `include`
or `exclude`, or set `n_components` to cluster on the principal components
that explain a given share of the variance, which merges redundant
aggregates of the same rows.

## Clusters with a definition

`RelationalClusteringTree` is a decision tree for clustering. It asks the
questions of a [relational tree](./relational-decision-trees), but chooses
each one to reduce the spread of the customers' features (the k-means
objective) instead of a prediction error. It stops at `n_clusters` leaves,
and each leaf is a cluster.

```python
from sklink.cluster import RelationalClusteringTree
from sklink.inspection import export_text

tree = RelationalClusteringTree(
    db, entity="customers", key="customer_id", n_clusters=4, min_samples_leaf=30
).fit(X)
print(export_text(tree, decimals=1))
```

```text
|--- count(orders) <= 7.5
|   |--- count(orders) <= 0.5
|   |   |--- cluster: 0
|   |--- count(orders) >  0.5
|   |   |--- cluster: 1
|--- count(orders) >  7.5
|   |--- proportion(orders[type == 'pickup']) <= 0.2
|   |   |--- cluster: 2
|   |--- proportion(orders[type == 'pickup']) >  0.2
|   |   |--- cluster: 3
```

The path from the root to a leaf defines its cluster. Clusters are numbered
in the order of the printout, and `labels_`, `predict` and
`cluster_centers_` use those numbers. `min_samples_leaf` keeps a single
unusual customer from becoming a cluster of its own.
`TreeDisplay.from_estimator(tree)`, from `sklink.plotting`, draws the tree with
one color per cluster, and `explain(tree, X)`, from `sklink.inspection`, gives each customer's path to its cluster.

## Which one to use

```python
print(f"k-means inertia {kmeans.inertia_:,.0f}")
print(f"tree inertia    {tree.inertia_:,.0f}")
```

```text
k-means inertia 34,760
tree inertia    34,808
```

Both inertias are measured on the same standardized features. That holds
because no column here has more than 10 categories: `max_categories`
defaults to 10 in `RelationalKMeans` and 32 in the tree, so set it equal in
both when you compare them on your data. K-means is free
to draw any boundary, so its clusters are usually tighter; here the tree's
four rules come close to it. The tree draws
boundaries that are questions about the database, which you can read, share
and turn into a SQL filter. A common workflow is to explore with
`RelationalKMeans`, then check whether a tree with the same number of
clusters gets close.

## Choose the number of clusters

The inertia always falls when clusters are added; look for the number after
which it falls much more slowly (the "elbow").

```python
for k in (2, 3, 4, 6, 8):
    model = RelationalKMeans(
        db,
        entity="customers",
        key="customer_id",
        n_clusters=k,
        n_init=5,
        random_state=0,
    ).fit(X)
    print(k, f"{model.inertia_:,.0f}")
```

```text
2 38,171
3 36,034
4 34,760
6 32,433
8 31,145
```

Choose the smallest number of clusters you can still tell apart and
describe; with no sharp elbow, readable clusters matter more than the last
bit of inertia.

The models are scikit-learn clusterers, so tools such as
`sklearn.metrics.adjusted_rand_score` compare two clusterings, and
`fit_predict` works in a `Pipeline`.

## Parameters at a glance

| Parameter | Default | What it does |
| --- | --- | --- |
| `n_clusters` | `8` | Number of clusters (maximum number of leaves for the tree) |
| `n_components` | `None` | Principal components to keep; a float keeps that share of the variance |
| `max_relationship_depth` | `2` | Relationships followed from the entity table |
| `min_samples_leaf` | `1` | Smallest cluster of the tree |
| `max_depth`, `max_conditions` | `None`, `1` | Depth of the tree and conditions per question, which bound how long a cluster's definition gets |
| `max_categories` | `10` (k-means), `32` (tree) | Most frequent categories of a column that get their own features or questions |
| `n_init`, `init`, `max_iter`, `tol` | as `KMeans` | K-means runs (`RelationalKMeans`) |
| `include`, `exclude` | `None` | Patterns that select the features (`RelationalKMeans`) |

With a `time` column, each customer is described only by the rows before
their cutoff, as in [Time and cutoffs](./time-and-cutoffs).
