DTime series · ts.hmm
Hidden Markov model (regimes in a sequence)
Does the sequence switch between a few hidden regimes — which ones, how long does each last, and when was each one in force?
Fits a hidden Markov model: a few hidden states that follow a first-order Markov chain, each emitting the observed values from its own Gaussian, Poisson or categorical distribution. Several sequences (sites, customers, sessions) share the parameters. Reports each state's mean, rate or most likely values, the transition probabilities, expected stays and long-run shares, the most probable state path (Viterbi) with the probability of each state at every step, and optionally AIC and BIC for 1 to K states. EM (Baum–Welch) from a deterministic start plus seeded random starts, identical in Python and R.
A real result
Example “Faithful waiting 2”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
A 2-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 55.44 (stay 1.08 steps); State 2 mean 80.53 (stay 1.72 steps). Log-likelihood -997.22, BIC 2033.7.
- Log-likelihood
- −997.22
- BIC
- 2033.68
- AIC
- 2008.44
Assumptions
- First-order Markov states — Assumed, not checked from the data: the next state depends only on the current one, the transition probabilities stay the same over time, and each observation depends only on its state.
- Same optimum from different starts — 3 of 3 starts reached the best log-likelihood (-997.2188).
States
| State | Mean | SD | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|---|
| State 1 | 55.436 | 6.609 | 6.777e-82 | 38.5% | 38.2% | 1.075 | 1.072 |
| State 2 | 80.527 | 5.478 | 1 | 61.5% | 61.8% | 1.716 | 1.714 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.0698 | 0.9302 |
| State 2 | 0.5828 | 0.4172 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 2 | 1 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 2 | 0.9997 |
| 4 | 62 | State 1 | 0.9979 |
| 5 | 85 | State 2 | 1.0000 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 2 | 1.0000 |
| 8 | 85 | State 2 | 1.0000 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 2 | 1.0000 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 2 | 1.0000 |
| 13 | 78 | State 2 | 0.9995 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 2 | 1.0000 |
| 16 | 52 | State 1 | 1.0000 |
| 17 | 62 | State 1 | 0.9626 |
| 18 | 84 | State 2 | 1.0000 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 2 | 1.0000 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.9999 |
| 24 | 69 | State 1 | 0.7240 |
| 25 | 74 | State 2 | 0.9706 |
| 26 | 83 | State 2 | 1.0000 |
| 27 | 55 | State 1 | 1.0000 |
| 28 | 76 | State 2 | 0.9985 |
| 29 | 78 | State 2 | 0.9917 |
| 30 | 79 | State 2 | 0.9961 |
| 31 | 73 | State 2 | 0.8381 |
| 32 | 77 | State 2 | 0.9988 |
| 33 | 66 | State 1 | 0.9598 |
| 34 | 80 | State 2 | 0.9998 |
| 35 | 74 | State 2 | 0.9946 |
| 36 | 52 | State 1 | 1.0000 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 2 | 1.0000 |
| 39 | 59 | State 1 | 0.9998 |
| 40 | 90 | State 2 | 1.0000 |
First 40 of 272 rows.
- EM (Baum–Welch) from 3 start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed 42; the best log-likelihood is kept. States are numbered by increasing mean, so labels don't switch between runs.
- Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.
- The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.
A 2-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 55.44 (stay 1.08 steps); State 2 mean 80.53 (stay 1.72 steps). Log-likelihood -997.22, BIC 2033.7.
- Log-likelihood
- −997.22
- BIC
- 2033.68
- AIC
- 2008.44
Assumptions
- First-order Markov states — Assumed, not checked from the data: the next state depends only on the current one, the transition probabilities stay the same over time, and each observation depends only on its state.
- Same optimum from different starts — 3 of 3 starts reached the best log-likelihood (-997.2188).
States
| State | Mean | SD | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|---|
| State 1 | 55.436 | 6.609 | 6.777e-82 | 38.5% | 38.2% | 1.075 | 1.072 |
| State 2 | 80.527 | 5.478 | 1.0000 | 61.5% | 61.8% | 1.716 | 1.714 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.0698 | 0.9302 |
| State 2 | 0.5828 | 0.4172 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 2 | 1.000 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 2 | 0.9997 |
| 4 | 62 | State 1 | 0.9979 |
| 5 | 85 | State 2 | 1.0000 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 2 | 1.0000 |
| 8 | 85 | State 2 | 1.0000 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 2 | 1.0000 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 2 | 1.0000 |
| 13 | 78 | State 2 | 0.9995 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 2 | 1.0000 |
| 16 | 52 | State 1 | 1.0000 |
| 17 | 62 | State 1 | 0.9626 |
| 18 | 84 | State 2 | 1.0000 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 2 | 1.0000 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.9999 |
| 24 | 69 | State 1 | 0.7240 |
| 25 | 74 | State 2 | 0.9706 |
| 26 | 83 | State 2 | 1.0000 |
| 27 | 55 | State 1 | 1.0000 |
| 28 | 76 | State 2 | 0.9985 |
| 29 | 78 | State 2 | 0.9917 |
| 30 | 79 | State 2 | 0.9961 |
| 31 | 73 | State 2 | 0.8381 |
| 32 | 77 | State 2 | 0.9988 |
| 33 | 66 | State 1 | 0.9598 |
| 34 | 80 | State 2 | 0.9998 |
| 35 | 74 | State 2 | 0.9946 |
| 36 | 52 | State 1 | 1.0000 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 2 | 1.0000 |
| 39 | 59 | State 1 | 0.9998 |
| 40 | 90 | State 2 | 1.0000 |
First 40 of 272 rows.
- EM (Baum–Welch) from 3 start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed 42; the best log-likelihood is kept. States are numbered by increasing mean, so labels don't switch between runs.
- Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.
- The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Faithful waiting 2h_faithful · value: waiting
- Faithful waiting 3 scanh_faithful · value: waiting
- Faithful shared varianceh_faithful · value: eruptions
- Sites gaussian sequencesseq_hmm · sequence: site · time: t · value: level
- Sites poisson countsseq_hmm · sequence: site · time: t · value: count
- Sites categorical weatherseq_hmm · sequence: site · time: t · value: weather
- Journeys categorical 3ds1_events · sequence: customer · time: minute · value: event
- Counts as categoriesseq_hmm · sequence: site · value: count
In the guides
Where it sits in the decision guides
- Sequences, curves and signals (hidden Markov models, functional PCA, scattering) · DS & ML Decision Guide · Discover — find structure without labels
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Observationnumeric / categorical · 1 column
- What is observed at each step: a number (Gaussian or Poisson states) or a category (categorical states).
- Sequence (optional)categorical · 0–1 column
- Separate sequences — sites, customers, sessions — that share the states; each starts afresh.
- Time (optional)temporal / numeric · 0–1 column
- Orders the steps within each sequence; omit to use the row order.
Choices you make
model
- Emission distributiondefault auto
How each state produces the observations.
- Automatic (Gaussian for numbers, categorical for categories)(default) — Gaussian states for a numeric column, categorical states for a categorical one.
- Gaussian — Each state has its own mean (and standard deviation): levels, measurements, returns.
- Poisson (counts) — Each state has its own rate: counts per step such as events, arrivals or defects.
- Categorical — Each state has its own probabilities over the values; numbers are treated as categories (at most 50).
- Number of statesdefault 2
How many hidden regimes to fit; compare several with the scan below.
- Spread of each statedefault state
Gaussian states only: whether each state has its own standard deviation.
- Each state its own(default) — States can differ in spread as well as level (calm and volatile regimes).
- Shared by all states — One standard deviation for every state: states differ only in their mean.
statistics
- Compare 1 to K statesdefault off
Also fit models with 1 to the number below of states and report log-likelihood, AIC and BIC (lower is better).
- Largest number of states to comparedefault 4
The comparison fits every number of states from 1 to this one.
Advanced
- Starting pointsdefault 3
EM runs from different starts (one deterministic, the rest random from the seed); the best fit is kept and the agreement is reported.
- Maximum EM iterationsdefault 300
Iterations per start before stopping; it stops earlier when the log-likelihood stops improving.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
First-order Markov statesNot checked from data: state why it holds
The next state depends only on the current one, transition probabilities stay the same over time, and each observation depends only on its state.
Same optimum from different starts
EM can stop at a local optimum; when several starts reach the same best log-likelihood the fit is more trustworthy.
What it reports
- n_obs
- Observations used (one per step) and the number of separate sequences that share the model.
- n_sequences
- Observations used (one per step) and the number of separate sequences that share the model.
- n_states
- A few hidden states follow a Markov chain; each state produces the observations from its own distribution.
- family
- A few hidden states follow a Markov chain; each state produces the observations from its own distribution.
- n_levels
- What each state produces: a mean and SD (Gaussian), a rate (Poisson) or probabilities over the values (categorical).
- loglik
- Log probability of all the sequences under the fitted model, summed over every path through the hidden states.
- n_params
- −2 log-likelihood plus 2 (AIC) or log n (BIC) per free parameter; lower is better when comparing numbers of states.
- aic
- −2 log-likelihood plus 2 (AIC) or log n (BIC) per free parameter; lower is better when comparing numbers of states.
- bic
- −2 log-likelihood plus 2 (AIC) or log n (BIC) per free parameter; lower is better when comparing numbers of states.
- iterations
- EM for a hidden Markov model: forward–backward gives each step's state probabilities, then the parameters are re-estimated.
- converged
- EM for a hidden Markov model: forward–backward gives each step's state probabilities, then the parameters are re-estimated.
- starts
- How many of the EM runs (one deterministic, the rest from the seed) reached the best log-likelihood, and which run won.
- starts_agree
- How many of the EM runs (one deterministic, the rest from the seed) reached the best log-likelihood, and which run won.
- best_start
- How many of the EM runs (one deterministic, the rest from the seed) reached the best log-likelihood, and which run won.
- switches
- The single most likely sequence of hidden states or labels given all the observations, found by dynamic programming.
Per group, level or term: pi[<k>], stationary[<k>], share[<k>], duration[<k>], mean_run[<k>], mean[<k>], sd[<k>], rate[<k>], prob[<k>:<level>], transition[<i>,<j>], scan_loglik[<k>], scan_aic[<k>], scan_bic[<k>], best_k_bic
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same twins (codesplash.stats.hmm ↔ codesplashr R/stats_hmm.R): scaled forward–backward, Baum–Welch updates in the same order, the same deterministic start (equal-count groups of the sorted values) and the same seeded starts (Wichmann–Hill stream), so they reach the same optimum; states are sorted by mean or rate (categorical: by the probability of the most common value) so labels never switch.
- hmmlearn 0.3.3 is the oracle (tests/crosscheck/w5seq_hmm.py): its forward algorithm gives the same log-likelihood at the fitted parameters, its Viterbi the same path and its posteriors the same state probabilities; its EM started from the twin's parameters gains no log-likelihood (≤ 1e-8 relative).
The exact script CodeSplash ran for example “Faithful waiting 2” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hidden Markov model (regimes in a sequence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.hmm 1.0.0 · spec f4a30f1592589bdf
# Dataset: h_faithful (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import hmm, ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/h_faithful.parquet", columns=["waiting"])
n_input = len(df)
df = df.dropna(subset=["waiting"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["waiting"]) # infinite values stop the run (registry/errors.yaml)
# %% Sequences
# A K-state hidden Markov model (Baum–Welch EM; Rabiner 1989): one observation per time step, several
# sequences sharing the parameters, states in a canonical order (increasing mean or rate).
VALUE = "waiting"
SEQUENCE = None
TIME = None
TEMPORAL = False
VALUE_CATEGORICAL = False
EMISSION = "auto"
K = int(2)
SHARED_VAR = False
STARTS = int(3)
SCAN = False
SCAN_MAX = int(4)
MAX_ITER = int(300)
SEED = 42
keys = ([SEQUENCE] if SEQUENCE else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
n = len(d)
cs.check_rows(n, max(10, 5 * K), "A hidden Markov model")
if VALUE_CATEGORICAL:
if EMISSION in ("gaussian", "poisson"):
cs.cs_error("CS_E_INVALID_OPTION", option="Emission distribution", allowed="categorical for a categorical column", value=EMISSION)
family = "categorical"
levels = [str(v) for v in d[VALUE].cat.categories]
check_groups(d[VALUE].astype(str), VALUE, minimum=2)
x_all = d[VALUE].cat.codes.to_numpy().astype(float)
else:
family = "gaussian" if EMISSION == "auto" else EMISSION
raw = d[VALUE].to_numpy(dtype=float)
check_not_constant(raw, VALUE)
if family == "categorical":
uniq = np.unique(raw)
if len(uniq) > 50:
cs.cs_error("CS_E_TOO_MANY_LEVELS", column=VALUE, k=len(uniq), max=50)
levels = ["%.6g" % v for v in uniq]
x_all = np.searchsorted(uniq, raw).astype(float)
else:
levels = []
x_all = raw
if family == "poisson":
bad = int(np.sum((raw < 0) | (raw != np.floor(raw))))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=VALUE, requirement="whole numbers of 0 or more (counts)", count=bad)
n_levels = len(levels)
seq_ids = [str(v) for v in d[SEQUENCE]] if SEQUENCE else ["1"] * n
seq_names = [str(v) for v in d[SEQUENCE].cat.categories] if SEQUENCE else ["1"]
bounds = []
start = 0
for i in range(1, n + 1):
if i == n or seq_ids[i] != seq_ids[i - 1]:
bounds.append((start, i))
start = i
seqs = [x_all[a:b] for a, b in bounds]
step = np.concatenate([np.arange(1, b - a + 1) for a, b in bounds])
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else []
if TIME:
dups = int(d.duplicated(subset=keys).sum())
if dups:
warnings.append(f"{dups} rows repeat a time within their sequence; they are kept in row order, one step each.")
# %% Fit
fit = hmm.fit(seqs, family, K, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
par, pi0, A = fit["par"], fit["pi"], fit["A"]
path = hmm.viterbi(seqs, family, par, pi0, A)
gamma = fit["gamma"]
statd = hmm.stationary(A)
N = len(x_all)
ll = fit["loglik"]
p_free = fit["n_params"]
values = {"n_obs": N, "n_sequences": len(seqs), "n_states": K, "family": family, "n_levels": n_levels,
"loglik": ll, "n_params": p_free, "aic": -2 * ll + 2 * p_free, "bic": -2 * ll + p_free * math.log(N),
"iterations": fit["iterations"], "converged": int(fit["converged"]), "starts": max(1, STARTS),
"starts_agree": fit["starts_agree"], "best_start": fit["start"]}
switches = 0
runs = {k: [] for k in range(K)}
for a, b in bounds:
r0 = a
for t in range(a + 1, b + 1):
if t == b or path[t] != path[t - 1]:
runs[int(path[t - 1])].append(t - r0)
if t < b:
switches += 1
r0 = t
values["switches"] = switches
state_names = [f"State {k + 1}" for k in range(K)]
rows = []
for k in range(K):
share = float(np.mean(path == k))
dur = 1.0 / (1.0 - A[k, k]) if A[k, k] < 1.0 else float("nan")
values[f"pi[{k + 1}]"] = float(pi0[k])
values[f"stationary[{k + 1}]"] = float(statd[k])
values[f"share[{k + 1}]"] = share
values[f"duration[{k + 1}]"] = dur
values[f"mean_run[{k + 1}]"] = float(np.mean(runs[k])) if runs[k] else float("nan")
row = {"state": state_names[k], "initial": float(pi0[k]), "stationary": float(statd[k]), "share": share,
"duration": dur, "mean_run": values[f"mean_run[{k + 1}]"]}
if family == "gaussian":
values[f"mean[{k + 1}]"] = float(par["mean"][k])
values[f"sd[{k + 1}]"] = float(math.sqrt(par["var"][k]))
row.update({"mean": float(par["mean"][k]), "sd": float(math.sqrt(par["var"][k]))})
elif family == "poisson":
values[f"rate[{k + 1}]"] = float(par["rate"][k])
row["rate"] = float(par["rate"][k])
else:
order = np.argsort(-par["prob"][k], kind="stable")[:3]
row["top"] = ", ".join(f"{levels[c]} ({par['prob'][k, c]:.2f})" for c in order)
for c in range(n_levels):
values[f"prob[{k + 1}:{levels[c]}]"] = float(par["prob"][k, c])
for j in range(K):
values[f"transition[{k + 1},{j + 1}]"] = float(A[k, j])
rows.append(row)
# %% Choosing the number of states
scan_rows = []
if SCAN:
for kk in range(1, SCAN_MAX + 1):
f_ = fit if kk == K else hmm.fit(seqs, family, kk, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
bic_ = -2 * f_["loglik"] + f_["n_params"] * math.log(N)
aic_ = -2 * f_["loglik"] + 2 * f_["n_params"]
scan_rows.append({"states": kk, "loglik": f_["loglik"], "params": f_["n_params"], "aic": aic_, "bic": bic_})
values[f"scan_loglik[{kk}]"] = f_["loglik"]
values[f"scan_aic[{kk}]"] = aic_
values[f"scan_bic[{kk}]"] = bic_
best = min(scan_rows, key=lambda r: r["bic"])
values["best_k_bic"] = best["states"]
for r in scan_rows:
r["best"] = "lowest BIC" if r["states"] == best["states"] else ""
# %% Assumptions
assumptions = [{"key": "markov", "label": "First-order Markov states", "status": "info",
"detail": "Assumed, not checked from the data: the next state depends only on the current one, the transition "
"probabilities stay the same over time, and each observation depends only on its state."}]
if max(1, STARTS) == 1:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "info",
"detail": "One start only: EM can stop at a local optimum; use several starts to check."})
elif fit["starts_agree"] >= 2:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "pass",
"detail": f"{fit['starts_agree']} of {max(1, STARTS)} starts reached the best log-likelihood ({ll:.4f})."})
else:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "warn",
"detail": f"Only start {fit['start']} of {max(1, STARTS)} reached the best log-likelihood ({ll:.4f}); the others stopped lower. "
"Add starts before trusting the states."})
# %% Charts
charts = []
first_n = bounds[0][1]
xs = labels[:first_n] if TIME else list(range(1, first_n + 1))
xkind = "temporal" if TEMPORAL else "numeric"
xname = TIME or "step"
first_title = f" ({SEQUENCE} {seq_names[0]})" if SEQUENCE and len(seqs) > 1 else ""
if family != "categorical":
charts.append(cs.chart("states", "segment-means", f"{VALUE} with the most probable states{first_title}", {
"x": cs.col(xname, xs, kind=xkind), "y": cs.col(VALUE, x_all[:first_n]),
"segment": cs.col("state", [state_names[int(s)] for s in path[:first_n]], kind="categorical")}))
if K > 1 and first_n <= 5000:
charts.append(cs.chart("posterior", "series-line", f"Probability of each state over time{first_title}", {
"x": cs.col(xname, [v for v in xs for _ in range(K)], kind=xkind),
"y": cs.col("probability", gamma[:first_n].reshape(-1)),
"group": cs.col("state", state_names * first_n, kind="categorical")}))
charts.append(cs.chart("transitions", "matrix-heatmap", "Transition probabilities (row = from, column = to)", {
"row": cs.col("from", [state_names[i] for i in range(K) for _ in range(K)], kind="categorical"),
"col": cs.col("to", [state_names[j] for _ in range(K) for j in range(K)], kind="categorical"),
"value": cs.col("probability", A.reshape(-1)),
"label": cs.col("text", [f"{v:.2f}" for v in A.reshape(-1)], kind="categorical")}))
if scan_rows:
charts.append(cs.chart("scan", "series-line", "Information criteria by number of states (lower is better)", {
"x": cs.col("states", [float(r["states"]) for r in scan_rows for _ in range(2)]),
"y": cs.col("criterion", [v for r in scan_rows for v in (r["aic"], r["bic"])]),
"group": cs.col("criterion name", ["AIC", "BIC"] * len(scan_rows), kind="categorical")}))
# %% Tables
state_cols = [{"key": "state", "label": "State", "type": "string"}]
if family == "gaussian":
state_cols += [{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}]
elif family == "poisson":
state_cols += [{"key": "rate", "label": "Rate", "type": "number"}]
else:
state_cols += [{"key": "top", "label": "Most likely values", "type": "string"}]
state_cols += [{"key": "initial", "label": "Initial probability", "type": "number"},
{"key": "stationary", "label": "Long-run share", "type": "percent"},
{"key": "share", "label": "Share of steps (most probable path)", "type": "percent"},
{"key": "duration", "label": "Expected stay (steps)", "type": "number"},
{"key": "mean_run", "label": "Mean run in path (steps)", "type": "number"}]
tables = [{"key": "states", "title": "States", "columns": state_cols, "rows": rows},
{"key": "transitions", "title": "Transition probabilities",
"columns": [{"key": "from", "label": "From", "type": "string"}] + [{"key": f"to{j + 1}", "label": f"To {state_names[j]}", "type": "number"} for j in range(K)],
"rows": [{"from": state_names[i], **{f"to{j + 1}": float(A[i, j]) for j in range(K)}} for i in range(K)]}]
if family == "categorical":
tables.append({"key": "emissions", "title": "Emission probabilities",
"columns": [{"key": "state", "label": "State", "type": "string"}] + [{"key": f"c{c + 1}", "label": levels[c], "type": "number"} for c in range(n_levels)],
"rows": [{"state": state_names[k], **{f"c{c + 1}": float(par["prob"][k, c]) for c in range(n_levels)}} for k in range(K)]})
if scan_rows:
tables.append({"key": "scan", "title": "Choosing the number of states",
"columns": [{"key": "states", "label": "States", "type": "integer"}, {"key": "loglik", "label": "Log-likelihood", "type": "number"},
{"key": "params", "label": "Parameters", "type": "integer"}, {"key": "aic", "label": "AIC", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}, {"key": "best", "label": "", "type": "string"}],
"rows": scan_rows})
CAP = 2000
shown = min(N, CAP)
path_rows = []
for i in range(shown):
path_rows.append({"sequence": seq_ids[i], "time": str(labels[i]) if TIME else str(int(step[i])),
"value": levels[int(x_all[i])] if family == "categorical" else float(x_all[i]),
"state": state_names[int(path[i])], "posterior": float(gamma[i, int(path[i])])})
tables.append({"key": "path", "title": "Most probable state of each step" + (f" (first {CAP} of {N})" if N > CAP else ""),
"columns": ([{"key": "sequence", "label": SEQUENCE, "type": "string"}] if SEQUENCE else [])
+ [{"key": "time", "label": TIME or "Step", "type": "string"},
{"key": "value", "label": VALUE, "type": "string" if family == "categorical" else "number"},
{"key": "state", "label": "State", "type": "string"},
{"key": "posterior", "label": "Probability of that state", "type": "number"}],
"rows": path_rows})
# %% Result
fam_label = {"gaussian": "Gaussian", "poisson": "Poisson", "categorical": "categorical"}[family]
where = f" over {len(seqs)} sequences" if len(seqs) > 1 else ""
if family == "gaussian":
desc = "; ".join(f"{state_names[k]} mean {par['mean'][k]:.4g} (stay {values[f'duration[{k + 1}]']:.3g} steps)" for k in range(K))
elif family == "poisson":
desc = "; ".join(f"{state_names[k]} rate {par['rate'][k]:.4g} (stay {values[f'duration[{k + 1}]']:.3g} steps)" for k in range(K))
else:
desc = "; ".join(f"{state_names[k]} mostly {levels[int(np.argmax(par['prob'][k]))]}" for k in range(K))
summary = f"A {K}-state hidden Markov model with {fam_label} emissions for {VALUE} ({N} steps{where}): {desc}. Log-likelihood {ll:.2f}, BIC {values['bic']:.1f}."
if not fit["converged"]:
warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what="The EM fit of the hidden Markov model"))
notes = [f"EM (Baum–Welch) from {max(1, STARTS)} start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed {SEED}; "
f"the best log-likelihood is kept. States are numbered by increasing "
+ ("mean" if family == "gaussian" else "rate" if family == "poisson" else "probability of the most common value, reversed") + ", so labels don't switch between runs.",
"Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.",
"The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step."]
statistics = [{"key": "loglik", "label": "Log-likelihood", "value": ll}, {"key": "bic", "label": "BIC", "value": values["bic"]},
{"key": "aic", "label": "AIC", "value": values["aic"]}]
cs.publish({
"method": "ts.hmm",
"methodVersion": "1.0.0",
"title": "Hidden Markov model",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Faithful waiting 2” · R version 4.5.1 (2025-06-13)
# Hidden Markov model (regimes in a sequence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.hmm 1.0.0 · spec f4a30f1592589bdf
# Dataset: h_faithful (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/h_faithful.parquet", col_select = c("waiting")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("waiting")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("waiting")) # infinite values stop the run (registry/errors.yaml)
# %% Sequences
# A K-state hidden Markov model (Baum-Welch EM; Rabiner 1989): one observation per time step, several
# sequences sharing the parameters, states in a canonical order (increasing mean or rate).
VALUE <- "waiting"
SEQUENCE <- NULL
TIME <- NULL
TEMPORAL <- FALSE
VALUE_CATEGORICAL <- FALSE
EMISSION <- "auto"
K <- as.integer(2)
SHARED_VAR <- FALSE
STARTS <- as.integer(3)
SCAN <- FALSE
SCAN_MAX <- as.integer(4)
MAX_ITER <- as.integer(300)
SEED <- 42
d <- df
if (!is.null(SEQUENCE) && !is.null(TIME)) {
d <- d[order(as.integer(d[[SEQUENCE]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SEQUENCE)) {
d <- d[order(as.integer(d[[SEQUENCE]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
n <- nrow(d)
cs_check_rows(n, max(10, 5 * K), "A hidden Markov model")
if (VALUE_CATEGORICAL) {
if (EMISSION %in% c("gaussian", "poisson"))
cs_error("CS_E_INVALID_OPTION", option = "Emission distribution", allowed = "categorical for a categorical column", value = EMISSION)
family <- "categorical"
levs <- as.character(levels(d[[VALUE]]))
cs_check_groups(as.character(d[[VALUE]]), VALUE, minimum = 2)
x_all <- as.integer(d[[VALUE]])
} else {
family <- if (EMISSION == "auto") "gaussian" else EMISSION
raw <- as.numeric(d[[VALUE]])
cs_check_not_constant(raw, VALUE)
if (family == "categorical") {
uniq <- sort(unique(raw))
if (length(uniq) > 50) cs_error("CS_E_TOO_MANY_LEVELS", column = VALUE, k = length(uniq), max = 50)
levs <- sprintf("%.6g", uniq)
x_all <- match(raw, uniq)
} else {
levs <- character(0)
x_all <- raw
if (family == "poisson") {
bad <- sum(raw < 0 | raw != floor(raw))
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = VALUE, requirement = "whole numbers of 0 or more (counts)", count = bad)
}
}
}
n_levels <- length(levs)
seq_ids <- if (!is.null(SEQUENCE)) as.character(d[[SEQUENCE]]) else rep("1", n)
seq_names <- if (!is.null(SEQUENCE)) as.character(levels(d[[SEQUENCE]])) else "1"
rl <- rle(seq_ids)
ends <- cumsum(rl$lengths)
starts_ <- ends - rl$lengths + 1
seqs <- lapply(seq_along(ends), function(i) x_all[starts_[i]:ends[i]])
step <- unlist(lapply(rl$lengths, seq_len), use.names = FALSE)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else list()
if (!is.null(TIME)) {
keycols <- c(SEQUENCE, TIME)
dups <- sum(duplicated(d[keycols]))
if (dups > 0) warnings <- c(warnings, sprintf("%d rows repeat a time within their sequence; they are kept in row order, one step each.", dups))
}
# %% Fit
fit <- cs_hmm_fit(seqs, family, K, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
par <- fit$par
pi0 <- fit$pi
A <- fit$A
path <- cs_hmm_viterbi(seqs, family, par, pi0, A)
gamma <- fit$gamma
statd <- cs_hmm_stationary(A)
N <- length(x_all)
ll <- fit$loglik
p_free <- fit$n_params
values <- list(n_obs = N, n_sequences = length(seqs), n_states = K, family = family, n_levels = n_levels,
loglik = ll, n_params = p_free, aic = -2 * ll + 2 * p_free, bic = -2 * ll + p_free * log(N),
iterations = fit$iterations, converged = as.integer(fit$converged), starts = max(1L, STARTS),
starts_agree = fit$starts_agree, best_start = fit$start)
switches <- 0
runs <- lapply(seq_len(K), function(k) numeric(0))
for (i in seq_along(ends)) {
a <- starts_[i]
b <- ends[i]
r0 <- a
for (t in (a + 1):(b + 1)) {
if (t == b + 1 || path[t] != path[t - 1]) {
s <- path[t - 1]
runs[[s]] <- c(runs[[s]], t - r0)
if (t <= b) switches <- switches + 1
r0 <- t
}
}
}
values$switches <- switches
state_names <- sprintf("State %d", seq_len(K))
rows <- list()
for (k in seq_len(K)) {
share <- mean(path == k)
dur <- if (A[k, k] < 1) 1 / (1 - A[k, k]) else NaN
values[[sprintf("pi[%d]", k)]] <- pi0[k]
values[[sprintf("stationary[%d]", k)]] <- statd[k]
values[[sprintf("share[%d]", k)]] <- share
values[[sprintf("duration[%d]", k)]] <- dur
values[[sprintf("mean_run[%d]", k)]] <- if (length(runs[[k]])) mean(runs[[k]]) else NaN
row <- list(state = state_names[k], initial = pi0[k], stationary = statd[k], share = share, duration = dur,
mean_run = values[[sprintf("mean_run[%d]", k)]])
if (family == "gaussian") {
values[[sprintf("mean[%d]", k)]] <- par$mean[k]
values[[sprintf("sd[%d]", k)]] <- sqrt(par$var[k])
row$mean <- par$mean[k]
row$sd <- sqrt(par$var[k])
} else if (family == "poisson") {
values[[sprintf("rate[%d]", k)]] <- par$rate[k]
row$rate <- par$rate[k]
} else {
o <- order(-par$prob[k, ], method = "radix")[seq_len(min(3, n_levels))]
row$top <- paste(sprintf("%s (%.2f)", levs[o], par$prob[k, o]), collapse = ", ")
for (cc in seq_len(n_levels)) values[[sprintf("prob[%d:%s]", k, levs[cc])]] <- par$prob[k, cc]
}
for (j in seq_len(K)) values[[sprintf("transition[%d,%d]", k, j)]] <- A[k, j]
rows[[k]] <- row
}
# %% Choosing the number of states
scan_rows <- list()
if (SCAN) {
for (kk in seq_len(SCAN_MAX)) {
f_ <- if (kk == K) fit else cs_hmm_fit(seqs, family, kk, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
bic_ <- -2 * f_$loglik + f_$n_params * log(N)
aic_ <- -2 * f_$loglik + 2 * f_$n_params
scan_rows[[kk]] <- list(states = kk, loglik = f_$loglik, params = f_$n_params, aic = aic_, bic = bic_)
values[[sprintf("scan_loglik[%d]", kk)]] <- f_$loglik
values[[sprintf("scan_aic[%d]", kk)]] <- aic_
values[[sprintf("scan_bic[%d]", kk)]] <- bic_
}
bics <- vapply(scan_rows, function(r) r$bic, numeric(1))
best_k <- scan_rows[[which.min(bics)]]$states
values$best_k_bic <- best_k
for (i in seq_along(scan_rows)) scan_rows[[i]]$best <- if (scan_rows[[i]]$states == best_k) "lowest BIC" else ""
}
# %% Assumptions
nst <- max(1L, STARTS)
assumptions <- list(list(key = "markov", label = "First-order Markov states", status = "info",
detail = paste0("Assumed, not checked from the data: the next state depends only on the current one, the transition ",
"probabilities stay the same over time, and each observation depends only on its state.")))
if (nst == 1) {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "info",
detail = "One start only: EM can stop at a local optimum; use several starts to check.")
} else if (fit$starts_agree >= 2) {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "pass",
detail = sprintf("%d of %d starts reached the best log-likelihood (%.4f).", fit$starts_agree, nst, ll))
} else {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "warn",
detail = sprintf("Only start %d of %d reached the best log-likelihood (%.4f); the others stopped lower. Add starts before trusting the states.",
fit$start, nst, ll))
}
# %% Charts
charts <- list()
first_n <- ends[1]
xs <- if (!is.null(TIME)) labels[seq_len(first_n)] else seq_len(first_n)
xkind <- if (TEMPORAL) "temporal" else "numeric"
xname <- if (is.null(TIME)) "step" else TIME
first_title <- if (!is.null(SEQUENCE) && length(seqs) > 1) sprintf(" (%s %s)", SEQUENCE, seq_names[1]) else ""
if (family != "categorical") {
charts[[length(charts) + 1]] <- cs_chart("states", "segment-means", sprintf("%s with the most probable states%s", VALUE, first_title), list(
x = cs_col(xname, xs, kind = xkind), y = cs_col(VALUE, x_all[seq_len(first_n)]),
segment = cs_col("state", state_names[path[seq_len(first_n)]], kind = "categorical")))
}
if (K > 1 && first_n <= 5000) {
charts[[length(charts) + 1]] <- cs_chart("posterior", "series-line", sprintf("Probability of each state over time%s", first_title), list(
x = cs_col(xname, rep(xs, each = K), kind = xkind),
y = cs_col("probability", as.vector(t(gamma[seq_len(first_n), , drop = FALSE]))),
group = cs_col("state", rep(state_names, times = first_n), kind = "categorical")))
}
charts[[length(charts) + 1]] <- cs_chart("transitions", "matrix-heatmap", "Transition probabilities (row = from, column = to)", list(
row = cs_col("from", rep(state_names, each = K), kind = "categorical"),
col = cs_col("to", rep(state_names, times = K), kind = "categorical"),
value = cs_col("probability", as.vector(t(A))),
label = cs_col("text", sprintf("%.2f", as.vector(t(A))), kind = "categorical")))
if (length(scan_rows)) {
charts[[length(charts) + 1]] <- cs_chart("scan", "series-line", "Information criteria by number of states (lower is better)", list(
x = cs_col("states", as.numeric(rep(vapply(scan_rows, function(r) r$states, numeric(1)), each = 2))),
y = cs_col("criterion", as.vector(rbind(vapply(scan_rows, function(r) r$aic, numeric(1)), vapply(scan_rows, function(r) r$bic, numeric(1))))),
group = cs_col("criterion name", rep(c("AIC", "BIC"), times = length(scan_rows)), kind = "categorical")))
}
# %% Tables
state_cols <- list(list(key = "state", label = "State", type = "string"))
if (family == "gaussian") {
state_cols <- c(state_cols, list(list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number")))
} else if (family == "poisson") {
state_cols <- c(state_cols, list(list(key = "rate", label = "Rate", type = "number")))
} else {
state_cols <- c(state_cols, list(list(key = "top", label = "Most likely values", type = "string")))
}
state_cols <- c(state_cols, list(list(key = "initial", label = "Initial probability", type = "number"),
list(key = "stationary", label = "Long-run share", type = "percent"),
list(key = "share", label = "Share of steps (most probable path)", type = "percent"),
list(key = "duration", label = "Expected stay (steps)", type = "number"),
list(key = "mean_run", label = "Mean run in path (steps)", type = "number")))
trans_cols <- c(list(list(key = "from", label = "From", type = "string")),
lapply(seq_len(K), function(j) list(key = sprintf("to%d", j), label = sprintf("To %s", state_names[j]), type = "number")))
trans_rows <- lapply(seq_len(K), function(i) c(list(from = state_names[i]), stats::setNames(as.list(A[i, ]), sprintf("to%d", seq_len(K)))))
tables <- list(list(key = "states", title = "States", columns = state_cols, rows = rows),
list(key = "transitions", title = "Transition probabilities", columns = trans_cols, rows = trans_rows))
if (family == "categorical") {
tables[[length(tables) + 1]] <- list(key = "emissions", title = "Emission probabilities",
columns = c(list(list(key = "state", label = "State", type = "string")),
lapply(seq_len(n_levels), function(cc) list(key = sprintf("c%d", cc), label = levs[cc], type = "number"))),
rows = lapply(seq_len(K), function(k) c(list(state = state_names[k]), stats::setNames(as.list(par$prob[k, ]), sprintf("c%d", seq_len(n_levels))))))
}
if (length(scan_rows)) {
tables[[length(tables) + 1]] <- list(key = "scan", title = "Choosing the number of states",
columns = list(list(key = "states", label = "States", type = "integer"), list(key = "loglik", label = "Log-likelihood", type = "number"),
list(key = "params", label = "Parameters", type = "integer"), list(key = "aic", label = "AIC", type = "number"),
list(key = "bic", label = "BIC", type = "number"), list(key = "best", label = "", type = "string")),
rows = scan_rows)
}
CAP <- 2000
shown <- min(N, CAP)
path_rows <- lapply(seq_len(shown), function(i) {
r <- list()
r$sequence <- seq_ids[i]
r$time <- if (!is.null(TIME)) as.character(labels[[i]]) else as.character(step[i])
r$value <- if (family == "categorical") levs[x_all[i]] else x_all[i]
r$state <- state_names[path[i]]
r$posterior <- gamma[i, path[i]]
r
})
path_cols <- c(if (!is.null(SEQUENCE)) list(list(key = "sequence", label = SEQUENCE, type = "string")) else list(),
list(list(key = "time", label = if (is.null(TIME)) "Step" else TIME, type = "string"),
list(key = "value", label = VALUE, type = if (family == "categorical") "string" else "number"),
list(key = "state", label = "State", type = "string"),
list(key = "posterior", label = "Probability of that state", type = "number")))
tables[[length(tables) + 1]] <- list(key = "path", title = paste0("Most probable state of each step", if (N > CAP) sprintf(" (first %d of %d)", CAP, N) else ""),
columns = path_cols, rows = path_rows)
# %% Result
fam_label <- c(gaussian = "Gaussian", poisson = "Poisson", categorical = "categorical")[[family]]
where <- if (length(seqs) > 1) sprintf(" over %d sequences", length(seqs)) else ""
desc <- if (family == "gaussian") {
paste(vapply(seq_len(K), function(k) sprintf("%s mean %s (stay %s steps)", state_names[k], formatC(par$mean[k], digits = 4, format = "g"),
formatC(values[[sprintf("duration[%d]", k)]], digits = 3, format = "g")), ""), collapse = "; ")
} else if (family == "poisson") {
paste(vapply(seq_len(K), function(k) sprintf("%s rate %s (stay %s steps)", state_names[k], formatC(par$rate[k], digits = 4, format = "g"),
formatC(values[[sprintf("duration[%d]", k)]], digits = 3, format = "g")), ""), collapse = "; ")
} else {
paste(vapply(seq_len(K), function(k) sprintf("%s mostly %s", state_names[k], levs[which.max(par$prob[k, ])]), ""), collapse = "; ")
}
summary <- sprintf("A %d-state hidden Markov model with %s emissions for %s (%d steps%s): %s. Log-likelihood %.2f, BIC %.1f.",
K, fam_label, VALUE, N, where, desc, ll, values$bic)
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = "The EM fit of the hidden Markov model"))
notes <- c(paste0(sprintf("EM (Baum–Welch) from %d start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed %d; ", nst, SEED),
"the best log-likelihood is kept. States are numbered by increasing ",
if (family == "gaussian") "mean" else if (family == "poisson") "rate" else "probability of the most common value, reversed",
", so labels don't switch between runs."),
"Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.",
"The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.")
statistics <- list(list(key = "loglik", label = "Log-likelihood", value = ll), list(key = "bic", label = "BIC", value = values$bic),
list(key = "aic", label = "AIC", value = values$aic))
cs_publish(list(
method = "ts.hmm",
methodVersion = "1.0.0",
title = "Hidden Markov model",
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Baum, L. E., Petrie, T., Soules, G., & Weiss, N. (1970). A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains. Annals of Mathematical Statistics, 41, 164–171.
- Rabiner, L. R. (1989). A tutorial on hidden Markov models and selected applications in speech recognition. Proceedings of the IEEE, 77, 257–286.
- Zucchini, W., MacDonald, I. L., & Langrock, R. (2016). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). CRC Press.
- Visser, I., & Speekenbrink, M. (2010). depmixS4: An R package for hidden Markov models. Journal of Statistical Software, 36(7), 1–21.
From the CodeSplash method registry · ts.hmm v1.0.0.