Segmentation of a data stream#

Three ways to segment data that arrive sample by sample: a multivariate CUSUM chart, recursive PCA (see the latent-variable examples) and a batch segmenter applied to a sliding buffer, which reports a change point once it is far enough from the end of the buffer to be stable.

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=6, length=200, n_variables=3, random_state=2
)

Windowed batch segmentation#

stream = sg.StreamSegmenter(
    sg.PELT("l2", jump=5), window=300, step=25, guard=20
)
reported = []
for t, x in enumerate(X):
    for c in stream.partial_fit(x):
        reported.append((t, c))
for t, c in reported:
    print(f"at sample {t:5d}: change point {c} (delay {t - c})")
at sample   229: change point 200 (delay 29)
at sample   429: change point 400 (delay 29)
at sample   629: change point 600 (delay 29)
at sample   829: change point 800 (delay 29)
at sample  1029: change point 1000 (delay 29)

Multivariate CUSUM#

cusum = sg.CUSUMDetector(k=0.5, h=25, warmup=50)
seg = cusum.segment(X)
print("CUSUM:", seg.change_points, "| true:", cps)
fig, axes = plt.subplots(2, 1, figsize=(7, 4.5), sharex=True)
mv.viz.plot_segmentation(X, seg, truth=cps, ax=axes[0])
mv.viz.plot_profile(
    cusum.statistic_,
    seg.change_points,
    ax=axes[1],
    label="CUSUM",
    threshold=cusum.h,
)
plt.show()
plot 06 streaming
CUSUM: [200 400 644 801 988] | true: [ 200  400  600  800 1000]

Total running time of the script: (0 minutes 0.232 seconds)

Gallery generated by Sphinx-Gallery