Tuning segmenter parameters#

Parameters can be tuned against labelled series by grid search on a segmentation metric, or without labels by maximizing stability. The sensitivity analysis of a single parameter shows how robust the method is.

import matplotlib.pyplot as plt
import numpy as np

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import (
    evaluate_segmentation,
    grid_search_segmenter,
    sensitivity,
)

train = [
    mv.datasets.make_correlation_switching(
        n_segments=4, length=150, n_variables=4, random_state=s
    )[:2]
    for s in range(4)
]

Sensitivity of BOCPD to the hazard#

X, cps = train[0]
res = sensitivity(
    lambda hazard: sg.BOCPD(hazard=hazard, model="full"),
    "hazard",
    [20, 50, 100, 200, 500, 1000],
    X,
    score=lambda s: evaluate_segmentation(cps, s, len(X), margin=10)["f1"],
)
for r in res:
    print(
        f"hazard {r['hazard']:5d}: {r['n_segments']} segments, F1 {r['score']:.2f}"
    )
fig, ax = plt.subplots(figsize=(5, 3))
ax.semilogx(
    [r["hazard"] for r in res],
    [r["score"] for r in res],
    "o-",
    color="#285780",
)
ax.set_xlabel("hazard")
ax.set_ylabel("F1")
ax.set_ylim(0, 1.05)
print("mean time per run (s):", np.mean([r["time"] for r in res]).round(3))
plt.show()
plot 04 tuning
hazard    20: 4 segments, F1 1.00
hazard    50: 4 segments, F1 1.00
hazard   100: 4 segments, F1 1.00
hazard   200: 4 segments, F1 1.00
hazard   500: 4 segments, F1 1.00
hazard  1000: 4 segments, F1 1.00
mean time per run (s): 0.121

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

Gallery generated by Sphinx-Gallery