Is the segmentation stable?#

Without ground truth, a segmentation can still be validated: change points that persist when the data are perturbed – noise added, a random block segmented – are trustworthy; those that come and go are not. The boundary frequency over the perturbed runs measures the support of every change point.

import matplotlib.pyplot as plt

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import segmentation_stability

X, cps, _ = mv.datasets.make_piecewise_stationary(
    n_segments=5,
    length=150,
    n_variables=3,
    change="all",
    vary=0.3,
    random_state=3,
)

Stable and unstable settings#

good = segmentation_stability(
    sg.BottomUp("normal", n_segments=5, initial_size=10),
    X,
    n_runs=20,
    random_state=0,
)
over = segmentation_stability(
    sg.BottomUp("normal", n_segments=9, initial_size=10),
    X,
    n_runs=20,
    random_state=0,
)
print(
    "5 segments: support",
    good["support"].round(2),
    "stability",
    round(good["stability"], 2),
)
print(
    "9 segments: support",
    over["support"].round(2),
    "stability",
    round(over["stability"], 2),
)
print(
    "change points with 9 segments:",
    over["reference"].change_points,
    "| true:",
    cps,
)
fig, axes = plt.subplots(2, 1, figsize=(7, 4.4), sharex=True)
mv.viz.plot_stability(good, ax=axes[0])
mv.viz.plot_stability(over, ax=axes[1])
stability = 0.86, stability = 0.89
5 segments: support [0.85 0.92 0.83 0.83] stability 0.86
9 segments: support [0.92 0.85 0.92 0.83 0.92 0.86 0.9  0.92] stability 0.89
change points with 9 segments: [120 130 260 270 450 460 620 630] | true: [123 261 454 626]

<Axes: title={'left': 'stability = 0.89'}, xlabel='time', ylabel='boundary frequency'>

Parameter study: the number of segments#

With too few segments the boundaries wander between runs; once every true change is found, the support saturates. The extra change points of the over-segmentation are stable as well, because they sit right next to the true ones (one initial segment away), so stability complements the rules for the number of segments rather than replacing them.

for k in range(3, 10):
    r = segmentation_stability(
        sg.BottomUp("normal", n_segments=k, initial_size=10),
        X,
        n_runs=15,
        random_state=0,
    )
    print(f"{k} segments: stability {r['stability']:.2f}")
plt.show()
3 segments: stability 0.46
4 segments: stability 0.57
5 segments: stability 0.83
6 segments: stability 0.82
7 segments: stability 0.83
8 segments: stability 0.85
9 segments: stability 0.87

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

Gallery generated by Sphinx-Gallery