How many segments?#

Five rules for the number of segments on one series: the knee of the cost curve, the relative reduction rate, BIC, a permutation test (after Vasko and Toivonen, 2002) and the persistence of the change points.

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import segmentation as sg
from mvtsa.datasets import make_piecewise_stationary

X, cps, _ = make_piecewise_stationary(
    n_segments=6, length=100, n_variables=2, random_state=11
)

The rules#

for method, kw in [
    ("knee", {}),
    ("rr", {"rr_threshold": 0.05}),
    ("bic", {}),
    ("persistence", {}),
    ("permutation", {"n_permutations": 19, "random_state": 0}),
]:
    n, info = sg.select_n_segments(
        X, "l2", method, max_segments=12, initial_size=5, **kw
    )
    print(f"{method:12s} -> {n} segments")
print("true number of segments:", len(cps) + 1)
knee         -> 5 segments
rr           -> 6 segments
bic          -> 6 segments
persistence  -> 6 segments
permutation  -> 6 segments
true number of segments: 6

BIC as a function of the number of segments#

n, info = sg.select_n_segments(X, "l2", "bic", max_segments=12, initial_size=5)
fig, ax = plt.subplots(figsize=(5, 3))
ks = sorted(info["bic"])
ax.plot(ks, [info["bic"][k] for k in ks], "o-")
ax.axvline(n, color="gray", ls=":")
ax.set_xlabel("number of segments")
ax.set_ylabel("BIC")
print(
    "BIC minimum at",
    n,
    "segments; min BIC",
    round(np.min(list(info["bic"].values())), 1),
)
plt.show()
plot 03 number of segments
BIC minimum at 6 segments; min BIC 498.3

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

Gallery generated by Sphinx-Gallery