Costs and search strategies#

Any cost can be combined with any search strategy. Here a piecewise stationary series with changes of the mean, the variance and the correlation is segmented with five costs and five strategies.

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import segmentation as sg
from mvtsa import viz
from mvtsa.datasets import make_piecewise_stationary
from mvtsa.evaluation import evaluate_segmentation

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

Five search strategies, Gaussian cost#

searches = {
    "bottom-up": sg.BottomUp("normal", n_segments=5, initial_size=10),
    "top-down": sg.TopDown("normal", n_segments=5, jump=5),
    "optimal": sg.OptimalPartition("normal", n_segments=5, jump=10),
    "PELT": sg.PELT("normal", penalty=250, jump=5, min_size=20),
    "window": sg.WindowDiscrepancy("normal", width=40, n_segments=5),
}
for name, s in searches.items():
    seg = s.segment(X)
    print(
        f"{name:10s}",
        seg.change_points,
        round(evaluate_segmentation(cps, seg, len(X), 10)["covering"], 3),
    )
viz.plot_segmentation(
    X,
    searches["PELT"].segment(X),
    truth=cps,
    title="PELT with the Gaussian cost",
)
PELT with the Gaussian cost
bottom-up  [180 320 500 610] 0.964
top-down   [179 319 498 604] 0.989
optimal    [184 314 494 604] 0.958
PELT       [180 320 495 605] 0.974
window     [177 318 498 603] 1.0

<Axes: title={'center': 'PELT with the Gaussian cost'}, xlabel='time'>

Parameter study: the PELT penalty#

The BIC default (about 60 here) over-segments this series because the variance changes make the Gaussian likelihood very sensitive; the penalty path shows how the number of change points settles as the penalty grows.

path = sg.penalty_path(
    X, "normal", penalties=[10, 20, 40, 80, 160, 250, 320, 640, 1280]
)
print(path)
fig, ax = plt.subplots(figsize=(5, 3))
ax.semilogx(list(path), list(path.values()), "o-")
ax.set_xlabel("penalty")
ax.set_ylabel("number of change points")
plt.show()
plot 01 costs and search
{10.0: 101, 20.0: 15, 40.0: 7, 80.0: 6, 160.0: 5, 250.0: 5, 320.0: 4, 640.0: 3, 1280.0: 0}

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

Gallery generated by Sphinx-Gallery