Recurring operating states#

Segments of a process often return to a few recurring states. Three ways to find them: a sticky Gaussian hidden Markov model, segmentation followed by clustering of the segments (with the 2-Wasserstein distance of their Gaussian descriptions), and a TICC-style model that assigns windows to sparse Gaussian graphical models with a switching penalty (Hallac et al., 2017).

import matplotlib.pyplot as plt
import pandas as pd

import mvtsa as mv
from mvtsa import segmentation as sg
from mvtsa.evaluation import evaluate_segmentation

R, cps, states = mv.datasets.make_regime_process(
    n_regimes=3, n_segments=8, length=150, random_state=1
)

Three state detectors#

models = {
    "sticky HMM": sg.GaussianHMMSegmenter(
        n_states=3, sticky=10, min_duration=10
    ),
    "segment + cluster": sg.StateSegmenter(n_states=3),
    "sparse Gaussian": sg.SparseGaussianStateSegmenter(
        n_states=3, window=2, beta=40
    ),
}
rows = []
for name, m in models.items():
    s = m.segment(R)
    rows.append(
        {
            "method": name,
            **evaluate_segmentation(
                cps, s, len(R), margin=10, true_states=states
            ),
        }
    )
print(pd.DataFrame(rows)[["method", "f1", "covering", "state_ari"]].round(3))
seg = models["segment + cluster"].segmentation_
fig, axes = plt.subplots(
    2, 1, figsize=(7, 4.2), sharex=True, gridspec_kw={"height_ratios": [3, 1]}
)
mv.viz.plot_segmentation(R, seg, truth=cps, ax=axes[0])
mv.viz.plot_states(seg, ax=axes[1])
plot 02 states
              method   f1  covering  state_ari
0         sticky HMM  1.0     0.980      0.969
1  segment + cluster  1.0     0.982      0.973
2    sparse Gaussian  1.0     0.985      0.977

<Axes: xlabel='time'>

How many states? BIC of the HMM#

h = sg.GaussianHMMSegmenter(n_states="bic", max_states=6, sticky=10).fit(R)
print(
    "BIC:", {k: round(v) for k, v in h.bic_.items()}, "-> states:", h.n_states_
)
small = min(range(h.n_states_), key=lambda k: (h.states_ == k).sum())
print(
    "samples of the smallest state:", (h.states_ == small).sum(), "around", cps
)
BIC: {1: 12433, 2: 7146, 3: 1790, 4: -152, 5: -64, 6: 11} -> states: 4
samples of the smallest state: 39 around [ 144  338  440  634  755  889 1069]

BIC asks for a fourth state: it collects the few samples of the smooth transitions between the regimes, which none of the three Gaussian regime models explains. Information criteria count such systematic deviations as structure; with min_duration the short visits are absorbed again.

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

Gallery generated by Sphinx-Gallery