Note
Go to the end to download the full example code or to run this example in your browser via Binder.
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)
]
Supervised grid search#
best, table = grid_search_segmenter(
lambda **p: sg.PCASegmenter(n_segments=4, **p),
{
"n_components": [1, 2, 3],
"statistic": ["Q", "T2", "both"],
"initial_size": [5, 10, 20],
},
train,
criterion="covering",
)
print("best:", best)
print(table.head(6).round(3).to_string(index=False))
best: {'n_components': 1, 'statistic': 'Q', 'initial_size': 5}
n_components statistic initial_size score
1 Q 5 1.000
1 Q 10 1.000
2 Q 5 0.988
1 Q 20 0.935
3 Q 10 0.925
2 Q 10 0.914
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()

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)