Chapter 9
Clustering
Clustering groups series, segments or moving objects. This chapter starts with partitional methods, which need a notion of a cluster centre – the arithmetic mean, the DBA or soft-DTW barycenter, the shape centroid of k-Shape, or a medoid – and continues with relational methods, which need only a distance matrix and therefore work with every measure of chapters 7 and 8. Maps of distance matrices, including the fuzzy Sammon mapping, show the structure of a collection. The last sections cluster features, segments and trajectories.
9.1 Partitional clustering
-means alternates between assigning every series to the nearest centre and recomputing the centres. For time series the two steps need an elastic distance and a matching average: the arithmetic mean with the Euclidean distance, DBA with DTW [33], or the soft-DTW barycenter with soft-DTW [29] (TimeSeriesKMeans, metric="euclidean", "dtw", "softdtw"). k-Shape uses the shape-based distance SBD and a centroid that maximizes the sum of squared normalized cross-correlations with the aligned members, the leading eigenvector of a matrix built from them [30] (KShape). The Odyssey benchmark found that none of 80 clustering methods outperformed k-Shape with a statistically significant difference [128], and a later study extended the comparison to 84 methods including deep learning and foundation models [129]; k-Shape is thus the natural baseline. When the centre is a member of the collection, any distance can be used: -medoids by partitioning around medoids [130] (KMedoids) and the relational fuzzy -medoids [131] (FuzzyCMedoids), whose memberships quantify the ambiguity of every assignment and feed the fuzzy Sammon mapping of section 9.3.
models = { "k-means (Euclidean)": cl.TimeSeriesKMeans( 6, metric="euclidean", random_state=0 ), "k-means (DBA)": cl.TimeSeriesKMeans( 6, metric="dtw", window=0.1, max_iter=10, random_state=0 ), "k-Shape": cl.KShape(6, random_state=0), "k-medoids (DTW)": cl.KMedoids( 6, metric="dtw", metric_params={"window": 0.1} ), "fuzzy c-medoids (DTW)": cl.FuzzyCMedoids( 6, metric="dtw", metric_params={"window": 0.1}, random_state=0 ), } rows = [] for name, m in models.items(): m.fit(C) rows.append({"algorithm": name, **clustering_scores(y, m.labels_)}) print(pd.DataFrame(rows).round(3).to_string(index=False))
9.2 Relational clustering
Relational methods take a distance matrix . Agglomerative hierarchical clustering merges the closest clusters under single, complete, average or Ward linkage and returns a dendrogram that can be cut at any level (HierarchicalClustering). Spectral clustering embeds the objects by the leading eigenvectors of a normalized affinity matrix, or a kernel such as GAK, and clusters the embedding [133] (SpectralClustering). DBSCAN and HDBSCAN find dense groups and leave outliers unassigned [134, 135] (DensityClustering). Consensus clustering accumulates the evidence of several clusterings in a co-association matrix – the fraction of clusterings that put two objects together – and clusters it hierarchically [136] (ConsensusClustering).
The choice of linkage matters more than one might expect. Average linkage tends to isolate a few outlying series in clusters of their own and leave one huge cluster when the number of clusters is fixed; Ward’s criterion and medoid-based methods give balanced partitions (fig. 9.2). On BasicMotions, recordings of four activities with a wrist-worn accelerometer and gyroscope [125], -medoids on CBDTW distances with the Gaussian Wasserstein local cost reaches an adjusted Rand index of 0.88, ahead of every other combination of the example.
D_dtw = pairwise_distances(C, metric="dtw_i", window=0.1) D_cb = ( wp.CBDTW(n_segments=6, n_components=2, local="gaussian_w2") .fit(C) .pairwise() ) models = { "Ward, DTW_I": cl.HierarchicalClustering( 4, linkage="ward", metric="precomputed" ).fit(D_dtw), "Ward, CBDTW (W2)": cl.HierarchicalClustering( 4, linkage="ward", metric="precomputed" ).fit(D_cb), "k-medoids, CBDTW (W2)": cl.KMedoids(4, metric="precomputed").fit(D_cb), "spectral, CBDTW (W2)": cl.SpectralClustering(4, metric="precomputed").fit( D_cb ), "features + k-means": cl.FeatureClustering(features="catch").fit(C), "signatures + k-means": cl.FeatureClustering( features="signature", signature_depth=2 ).fit(C), } models["consensus"] = cl.ConsensusClustering(n_clusters=4).fit_partitions( [m.labels_ for m in models.values()] ) rows = [ {"model": k, **clustering_scores(y, m.labels_)} for k, m in models.items() ] print(pd.DataFrame(rows).round(3).to_string(index=False))
Open in ColabExample plot_03_basic_motions.py in the gallery
9.3 Maps of distance matrices
A distance matrix is easier to understand as a picture. Sammon mapping places the objects in the plane so that their distances match the original ones, with small distances weighted more [137] (sammon); metric MDS and t-SNE are the alternatives of plot_embedding. For a fuzzy clustering, the fuzzy Sammon mapping of Feil, Balaskó and Abonyi maps the objects relative to the cluster prototypes, preserving the distances to the prototypes weighted by the memberships [18] (fuzzy_sammon). It needs only distances instead of , so it scales to large collections, and it shows the clusters with the prototypes at their centres (fig. 9.3). Ordering a distance matrix by the clusters (plot_distance_matrix) and the dendrogram complete the views.
fcm = cl.FuzzyCMedoids(3, metric="precomputed", random_state=0).fit(D) Y_fuzzy, Z_proto = viz.fuzzy_sammon(D, fcm.memberships_, fcm.medoid_indices_)
Open in ColabExample plot_02_hierarchical_maps.py in the gallery
9.4 Features, segments and trajectories
Features. Clustering the feature vectors or path signatures of section 3.4 with any vector clusterer is fast, handles series of different lengths and gives interpretable clusters (FeatureClustering).
Segments. Clustering the segments of many series instead of whole series yields a vocabulary of operating patterns: every series becomes a sequence of pattern labels, and the patterns can be compared across batches, shifts or units (SegmentClustering). The segment models are the Gaussian or PCA descriptors of section 6.2, compared by the 2-Wasserstein distance or by PCA similarity in the spirit of Singhal and Seborg [93]. In fig. 9.4, six batches cut from one process with three recurring regimes are segmented and their segments clustered; the sample-level agreement of the pattern labels with the true regimes reaches an adjusted Rand index of 0.90.
sc = cl.SegmentClustering( segmenter=sg.BottomUp("normal", penalty=60, initial_size=20), n_clusters=3 ).fit(C) for i, seg in enumerate(sc.segmentations_): print( f"series {i}: {seg.n_segments} segments, patterns {seg.labels.tolist()}" ) pred = np.concatenate( [seg.to_labels(states=True) for seg in sc.segmentations_] ) true = np.concatenate( [ mv.Segmentation(c, len(x), labels=st).to_labels(states=True) for x, (c, st) in zip(C, series, strict=True) ] ) print( "sample-level agreement with the true regimes:", clustering_scores(true, pred), )
Open in ColabExample plot_04_segment_clustering.py in the gallery
Trajectories. When many objects – units, sensors, customers, countries – move in a common phase space, two questions arise: which objects follow similar paths, and which stay neighbours over time. Tarcsay, Abonyi and Németh answer the second with the neighbourhood preservation of the objects: the share of time steps at which two objects are among each other’s nearest neighbours [19]. DBSCAN on one minus this similarity yields groups of co-moving objects, and repeating the analysis in consecutive windows shows how the groups evolve (TrajectoryClustering; method="trajectory" clusters by the mean distance of whole trajectories instead).
tc = cl.TrajectoryClustering(method="neighborhood", k=6, window=20).fit(P) print("labels:", tc.labels_) print( "labels per 20-step window:", [lab.tolist()[:6] for lab in tc.labels_window_], )
In a nutshell: Clustering
Partitional methods need a centre: the mean, the DBA or soft-DTW barycenter, the k-Shape centroid, or a medoid; k-Shape is the strongest simple baseline. Relational methods – hierarchical, spectral, density-based, consensus, -medoids and fuzzy -medoids – work with any distance matrix; Ward’s criterion and medoids give balanced partitions where average linkage isolates outliers. Sammon and fuzzy Sammon maps show distance matrices and fuzzy clusterings. Features and signatures, segments and trajectories are clustered with the same tools. In mvtsa: TimeSeriesKMeans, KShape, KMedoids, FuzzyCMedoids, HierarchicalClustering, SpectralClustering, DensityClustering, ConsensusClustering, FeatureClustering, SegmentClustering, TrajectoryClustering, sammon, fuzzy_sammon.