Clustering: Partitioning Around Medoids (PAM)#

This example demonstrates Partitioning Around Medoids (PAM) clustering, which finds k representative objects (medoids) that minimize total distance to all assigned objects.

Setup#

import polars as pl

from tanat import build_states
from tanat.clustering import PAMClusterer
from tanat.dataset import simulate_states
from tanat.metric.entity import HammingEntityMetric
from tanat.metric.sequence import EditSequenceMetric

Generate synthetic data#

N_IDS = 50
SEED = 42

raw_df = simulate_states(
    n_ids=N_IDS,
    seq_length_range=(3, 8),
    features=["score", "status"],
    seed=SEED,
)

pool = build_states(
    temporal_data=raw_df,
    id_column="id",
    start_column="start",
    end_column="end",
)
┌─ State SequenceStore
│
│ Step 1/4: Sorting & preparing data
│
│ Step 2/4: Building sequence index
│
│ Step 3/4: Writing entity & time index features
│
│ Step 4/4: Computing & writing metadata
│
└─ Done (50 sequences · 288 entities · 0.00s)
# Cast features to categorical
pool.cast_features({"status": pl.Categorical})
print(pool)
┌────────────────────────────────────────────────┐
│           StateSequencePool Summary            │
└────────────────────────────────────────────────┘

Overview
─────────────────────────
  Sequences          50
  Store              /home/runner/.tanat/_quick_state_db97efb8
  id_column          id

Time Index
─────────────────────────
  Type               Datetime(time_unit='us', time_zone=None) [2000-03-07 19:05:41.124579 → 2025-02-13 19:08:47.918854]
  Columns            ['start', 'end']
  t0                 position=0, anchor=start

Entity Features (2)
─────────────────────────
  • score               Numerical [1 → 100]
  • status              Categorical (5 categories)

Define the metric used by the clusterer#

hamming = HammingEntityMetric(entity_feature="status")
metric = EditSequenceMetric(entity_metric=hamming, normalize=True)

Perform PAM clustering#

n_clusters = 5

clusterer = PAMClusterer(metric=metric, n_clusters=n_clusters)
clusterer.fit(pool)
┌─ PAMClusterer
│
│ Step 1/2: Computing distance matrix
│
│   ┌─ EditSequenceMetric
│   │

│   │ Chunks:   0%|          | 0/1 [00:00<?, ?it/s]
│   │ Chunks: 100%|██████████| 1/1 [00:00<00:00, 2803.68it/s]
│   │
│   └─ Done (50 sequences · 0.00s)
│
│ Step 2/2: Clustering (PAMClusterer)
│
└─ Done (50 items, 5 clusters · 1.43s)

PAMClusterer(clusters=5)
# Clustering results
print(clusterer)
┌────────────────────────────────────────────────┐
│                  PAMClusterer                  │
└────────────────────────────────────────────────┘

Settings
─────────────────────────
  n_clusters         5
  max_iter           50
  metric             EditSequenceMetric
  cluster_column     __PAM_CLUSTERS__

Results
─────────────────────────
  Clusters           5
  Avg size           10.0
  Min size           4
  Max size           15

Clusters
─────────────────────────
  #0                 14 items
  #1                 15 items
  #2                 9 items
  #3                 8 items
  #4                 4 items

Inspect cluster assignments and medoids#

print("\nMedoids (representative sequences):")
for i, medoid_id in enumerate(clusterer.medoids):
    print(f"  Cluster {i}: {medoid_id}")

print("\nCluster assignments injected as static features:")
print(pool.static_data().head())
Medoids (representative sequences):
  Cluster 0: 5
  Cluster 1: 21
  Cluster 2: 30
  Cluster 3: 4
  Cluster 4: 22

Cluster assignments injected as static features:
   id  __PAM_CLUSTERS__
0   1                 2
1   2                 0
2   3                 1
3   4                 3
4   5                 0

Total running time of the script: (0 minutes 1.449 seconds)

Gallery generated by Sphinx-Gallery