Clustering with Precomputed Distance Matrices

This example demonstrates how to use CLARANS and FastCLARANS with precomputed pairwise distance matrices (metric=’precomputed’), enabling clustering on graph, geodesic, or custom non-Euclidean distance data.

Sorted Precomputed Distance Matrix by Clusters
CLARANS Medoids:     [ 4 17 64] | Cost: 582.51
FastCLARANS Medoids: [ 4 17 64] | Cost: 582.51

# Authors: Ngọc Thiện Nguyễn <thiennguyen03001@gmail.com>
# License: MIT

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.metrics import pairwise_distances
from clarans import CLARANS, FastCLARANS


X, _ = make_blobs(n_samples=180, centers=3, n_features=4, random_state=42)
# Precompute pairwise Manhattan distances
D = pairwise_distances(X, metric="manhattan")

# Fit CLARANS
model_clarans = CLARANS(n_clusters=3, num_local=3, metric="precomputed", random_state=42)
model_clarans.fit(D)

# Fit FastCLARANS
model_fast = FastCLARANS(n_clusters=3, num_local=3, metric="precomputed", random_state=42)
model_fast.fit(D)

print(
    f"CLARANS Medoids:     {model_clarans.medoid_indices_} | "
    f"Cost: {model_clarans.inertia_:.2f}"
)
print(
    f"FastCLARANS Medoids: {model_fast.medoid_indices_} | "
    f"Cost: {model_fast.inertia_:.2f}"
)

# Distance matrix sorted by cluster assignment
sort_idx = model_clarans.labels_.argsort()
D_sorted = D[sort_idx, :][:, sort_idx]

plt.figure(figsize=(6, 5))
plt.imshow(D_sorted, cmap="viridis", origin="lower")
plt.colorbar(label="Manhattan Distance")
plt.title("Sorted Precomputed Distance Matrix by Clusters")
plt.tight_layout()
plt.show()

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

Related examples

Benchmarking CLARANS vs. FastCLARANS Convergence Speed

Benchmarking CLARANS vs. FastCLARANS Convergence Speed

Clustering on Asymmetric Precomputed Distance Matrices (D != D^T)

Clustering on Asymmetric Precomputed Distance Matrices (D != D^T)

Distance Metrics and Metric Parameters in CLARANS Clustering

Distance Metrics and Metric Parameters in CLARANS Clustering

Clustering Non-Vector Data: Text Sequences with Edit Distance

Clustering Non-Vector Data: Text Sequences with Edit Distance

Gallery generated by Sphinx-Gallery