Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Clustering segments: recurring patterns across series#
Instead of clustering whole series, every series is segmented and the segments of all series are clustered. The result is a vocabulary of operating patterns: each series becomes a sequence of pattern labels, and the patterns can be compared across batches, shifts or units.
import matplotlib.pyplot as plt
import numpy as np
import mvtsa as mv
from mvtsa import clustering as cl
from mvtsa import segmentation as sg
from mvtsa import viz
from mvtsa.datasets import make_regime_process
from mvtsa.evaluation import clustering_scores
# Six series (batches) cut from one process with three recurring regimes,
# five regime segments each.
X, cps, states = make_regime_process(
n_regimes=3, n_segments=30, length=120, random_state=0
)
bounds = np.r_[0, cps[4::5], len(X)]
C, series = [], []
for k in range(6):
a, b = bounds[k], bounds[k + 1]
C.append(X[a:b])
series.append((cps[(cps > a) & (cps < b)] - a, states[5 * k : 5 * k + 5]))
Segment and cluster#
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),
)
seg0 = sc.segmentations_[0]
viz.plot_segmentation(
C[0],
seg0,
truth=series[0][0],
title="series 0, segments coloured by pattern",
)
plt.show()

series 0: 9 segments, patterns [0, 2, 2, 1, 1, 1, 0, 2, 2]
series 1: 10 segments, patterns [0, 0, 1, 0, 0, 2, 2, 1, 1, 1]
series 2: 11 segments, patterns [0, 0, 1, 1, 1, 2, 0, 0, 0, 2, 2]
series 3: 10 segments, patterns [0, 2, 2, 2, 1, 1, 2, 2, 1, 1]
series 4: 12 segments, patterns [0, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 1]
series 5: 10 segments, patterns [2, 2, 1, 1, 0, 0, 0, 1, 2, 2]
sample-level agreement with the true regimes: {'ari': 0.9020377359823869, 'ami': 0.8507920234072378, 'nmi': 0.8508675868750745, 'purity': 0.9663982227159122, 'accuracy': 0.9663982227159122}
Total running time of the script: (0 minutes 0.150 seconds)