Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Hierarchical clustering and distance maps#
Hierarchical clustering of a distance matrix shows the structure of a collection at every level. Sammon mapping (Sammon, 1969) draws the matrix in two dimensions while preserving small distances; the fuzzy Sammon mapping (Feil, Balaskó and Abonyi, 2007) maps the objects relative to the cluster prototypes using the fuzzy memberships, which makes the map of a large collection fast and faithful to the clustering.
import matplotlib.pyplot as plt
import numpy as np
from mvtsa import clustering as cl
from mvtsa import pairwise_distances, viz
from mvtsa.datasets import make_cbf
from mvtsa.evaluation import clustering_scores
C, y = make_cbf(n_per_class=20, random_state=1)
D = pairwise_distances(C, metric="dtw", window=0.1)
Dendrogram and ordered distance matrix#
hc = cl.HierarchicalClustering(
n_clusters=3, linkage="average", metric="precomputed"
).fit(D)
print(clustering_scores(y, hc.labels_))
viz.plot_dendrogram(hc.linkage_matrix_, labels=y, truncate=30)
viz.plot_distance_matrix(D, hc.labels_)
{'ari': 0.35748971958754366, 'ami': 0.4398821099950448, 'nmi': 0.4589753715390286, 'purity': 0.75, 'accuracy': 0.75}
<Axes: >
Sammon and fuzzy Sammon maps#
fcm = cl.FuzzyCMedoids(3, metric="precomputed", random_state=0).fit(D)
Y_fuzzy, Z_proto = viz.fuzzy_sammon(D, fcm.memberships_, fcm.medoid_indices_)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
viz.plot_embedding(D, y, method="sammon", ax=axes[0])
for k in np.unique(y):
axes[1].scatter(*Y_fuzzy[y == k].T, s=22, label=str(k))
axes[1].scatter(*Z_proto.T, marker="*", s=200, color="k", label="prototypes")
axes[1].set_title("fuzzy Sammon mapping")
axes[1].legend(frameon=False)

/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/sklearn/manifold/_mds.py:735: FutureWarning: The default value of `init` will change from 'random' to 'classical_mds' in 1.10. To suppress this warning, provide some value of `init`.
warnings.warn(
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/sklearn/manifold/_mds.py:752: FutureWarning: The `dissimilarity` parameter is deprecated and will be removed in 1.10. Use `metric` instead.
warnings.warn(
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/sklearn/manifold/_mds.py:735: FutureWarning: The default value of `init` will change from 'random' to 'classical_mds' in 1.10. To suppress this warning, provide some value of `init`.
warnings.warn(
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/sklearn/manifold/_mds.py:752: FutureWarning: The `dissimilarity` parameter is deprecated and will be removed in 1.10. Use `metric` instead.
warnings.warn(
<matplotlib.legend.Legend object at 0x773c661f18e0>
Parameter study: the linkage#
Cylinder and bell differ only in which side of the plateau rises slowly, so they are hard to separate without labels: the clustering task is much harder than 1-NN classification on the same distances.
for link in ("single", "complete", "average", "ward"):
lab = (
cl.HierarchicalClustering(3, linkage=link, metric="precomputed")
.fit(D)
.labels_
)
print(
f"{link:8s} ARI {clustering_scores(y, lab)['ari']:.3f} cluster sizes {np.bincount(lab).tolist()}"
)
plt.show()
single ARI 0.020 cluster sizes [4, 55, 1]
complete ARI 0.080 cluster sizes [47, 5, 8]
average ARI 0.357 cluster sizes [11, 16, 33]
ward ARI 0.142 cluster sizes [8, 23, 29]
Total running time of the script: (0 minutes 0.366 seconds)

