Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Clustering multivariate recordings: BasicMotions#
Forty recordings of four activities (standing, walking, running, badminton) from a wrist-worn accelerometer and gyroscope (UEA archive). Elastic measures, correlation-based warping, interpretable features and path signatures (Chen, 1958; Lyons, 2014) are compared as bases for clustering, and consensus clustering combines them.
import matplotlib.pyplot as plt
import pandas as pd
from mvtsa import clustering as cl
from mvtsa import pairwise_distances, viz
from mvtsa import warping as wp
from mvtsa.datasets import load_basic_motions
from mvtsa.evaluation import clustering_scores
C, y = load_basic_motions()
Distance-based and feature-based clustering#
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))
model ari ami nmi purity accuracy
Ward, DTW_I 0.675 0.821 0.829 0.750 0.725
Ward, CBDTW (W2) 0.651 0.805 0.815 0.750 0.700
k-medoids, CBDTW (W2) 0.876 0.902 0.906 0.950 0.950
spectral, CBDTW (W2) 0.622 0.791 0.802 0.750 0.650
features + k-means 0.675 0.791 0.798 0.750 0.750
signatures + k-means 0.592 0.746 0.754 0.712 0.712
consensus 0.651 0.805 0.815 0.750 0.700
Average linkage isolates a few outlying recordings in clusters of their own and leaves one huge cluster (try it); Ward’s criterion and the medoid-based methods give balanced partitions. The interpretable features and the Gaussian segment models carry most of the information.
viz.plot_embedding(D_cb, y, method="sammon")
plt.show()

/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(
Total running time of the script: (0 minutes 7.855 seconds)