Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Benchmarking segmenters with statistical tests#
A fair comparison runs every method on many data sets and tests whether the differences are significant. The Friedman test checks whether the average ranks differ at all; the Nemenyi critical difference (Demšar, 2006) tells which pairs differ. Here ten synthetic series with changes of the mean, the variance and the correlation are segmented by eight methods.
import matplotlib.pyplot as plt
import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import Benchmark, friedman_nemenyi, wilcoxon_holm
datasets = {
f"series {i}": mv.datasets.make_piecewise_stationary(
n_segments=5,
length=120,
n_variables=3,
change="all",
vary=0.3,
random_state=i,
)[:2]
for i in range(10)
}
Run the benchmark#
methods = {
"BU-L2": lambda: sg.BottomUp("l2", n_segments=5, initial_size=10),
"BU-Gauss": lambda: sg.BottomUp("normal", n_segments=5, initial_size=10),
"BU-kernel": lambda: sg.BottomUp("kernel", n_segments=5, initial_size=10),
"TD-Gauss": lambda: sg.TopDown("normal", n_segments=5, jump=5),
"Opt-Gauss": lambda: sg.OptimalPartition("normal", n_segments=5, jump=10),
"Window": lambda: sg.WindowDiscrepancy("normal", width=30, n_segments=5),
"BOCPD": lambda: sg.BOCPD(hazard=120),
"PCA-Q": lambda: sg.PCASegmenter(n_segments=5, n_components=1),
}
bench = Benchmark(methods, datasets)
res = bench.run()
print(
res.groupby("method")[["f1", "covering", "time"]]
.mean()
.sort_values("covering", ascending=False)
.round(3)
)
f1 covering time
method
Window 1.000 0.999 0.018
TD-Gauss 1.000 0.980 0.010
BU-kernel 1.000 0.968 0.013
BU-L2 0.950 0.964 0.001
Opt-Gauss 0.950 0.958 0.022
BU-Gauss 0.725 0.946 0.002
PCA-Q 0.875 0.944 0.004
BOCPD 0.946 0.940 0.112
Friedman test and critical difference diagram#
stat = friedman_nemenyi(bench.pivot("covering"))
print(
f"Friedman p = {stat['p_value']:.2g}, CD = {stat['critical_difference']:.2f}"
)
print(
wilcoxon_holm(bench.pivot("covering"))
.head(5)
.round(4)
.to_string(index=False)
)
mv.viz.plot_critical_difference(
stat["ranks"], stat["critical_difference"], title="covering, 10 series"
)
plt.show()

Friedman p = 7.7e-06, CD = 3.32
method_a method_b p_value p_holm significant
BU-Gauss Window 0.002 0.0547 False
BU-Gauss TD-Gauss 0.002 0.0547 False
BU-kernel Window 0.002 0.0547 False
TD-Gauss Window 0.002 0.0547 False
Opt-Gauss Window 0.002 0.0547 False
Total running time of the script: (0 minutes 2.148 seconds)