Note
Go to the end to download the full example code or to run this example in your browser via Binder.
First steps: segment, look, evaluate#
A multivariate series of three variables whose correlation structure switches three times – the means and variances stay the same, so no variable shows the changes on its own. A PCA-based bottom-up segmentation (Abonyi et al., 2005) finds them, and the result is compared with the truth.
Data and segmentation#
import matplotlib.pyplot as plt
import mvtsa as mv
from mvtsa.evaluation import evaluate_segmentation
X, true_cps, states = mv.datasets.make_correlation_switching(
n_segments=4, length=150, random_state=0
)
seg = mv.segment(
X, "pca", n_segments=4, n_components=1
) # Q-statistic cost, bottom-up search
print(seg)
print(evaluate_segmentation(true_cps, seg, len(X), margin=5))
Segmentation(n_segments=4, n_samples=600, change_points=[150, 300, 450], method='PCASegmenter')
{'precision': 1.0, 'recall': 1.0, 'f1': 1.0, 'tp': 3, 'covering': 1.0, 'hausdorff': 0.0, 'annotation_error': 0, 'n_true': 3, 'n_pred': 3, 'margin': 5, 'segment_ari': 1.0}
The segmented series#
Segments are shaded, detected change points are blue lines, the true ones orange marks at the top.
mv.viz.plot_segmentation(X, seg, truth=true_cps, names=["x1", "x2", "x3"])

<Axes: xlabel='time'>
The same series segmented by the means only#
A piecewise-constant (L2) cost cannot see correlation changes.
seg_l2 = mv.segment(X, "bottomup", cost="l2", n_segments=4)
print(
"L2 change points:",
seg_l2.change_points,
" PCA change points:",
seg.change_points,
)
mv.viz.plot_segmentation(X, seg_l2, truth=true_cps, names=["x1", "x2", "x3"])
plt.show()

L2 change points: [129 496 510] PCA change points: [150 300 450]
Total running time of the script: (0 minutes 0.727 seconds)