Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Partitional clustering: k-means, k-Shape, k-medoids#
Partitional clustering needs a distance and a notion of a cluster centre.
TimeSeriesKMeans averages with the arithmetic
mean (Euclidean), DBA (DTW; Petitjean et al., 2011) or the soft-DTW
barycenter; k-Shape (Paparrizos and Gravano, 2015) uses the shape-based
distance and a centroid computed from the leading eigenvector; k-medoids and
fuzzy c-medoids only need a distance matrix, so any elastic measure works.
The synthetic control chart data (Alcock and Manolopoulos, 1999) have six
classes: normal, cyclic, increasing and decreasing trends, upward and
downward shifts.
import matplotlib.pyplot as plt
import pandas as pd
from mvtsa import clustering as cl
from mvtsa import viz
from mvtsa.datasets import make_synthetic_control
from mvtsa.evaluation import clustering_scores
C, y = make_synthetic_control(n_per_class=15, random_state=0)
Five algorithms#
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))
dba = models["k-means (DBA)"]
viz.plot_cluster_prototypes(
C, dba.labels_, centers=dba.cluster_centers_, ncols=3
)
plt.show()

algorithm ari ami nmi purity accuracy
k-means (Euclidean) 0.570 0.704 0.731 0.767 0.767
k-means (DBA) 0.594 0.725 0.751 0.744 0.678
k-Shape 0.527 0.613 0.649 0.744 0.700
k-medoids (DTW) 0.759 0.817 0.834 0.878 0.878
fuzzy c-medoids (DTW) 0.759 0.817 0.834 0.878 0.878
Total running time of the script: (0 minutes 1.320 seconds)