Hidden regimes: hidden Markov models
When a series switches between a few regimes and back again, a hidden Markov model finds the regimes, how long each lasts, and which one was in force at every step.
What runs in CodeSplash
- Hidden Markov model (regimes in a sequence) Verified in Python and R
You will be able to
- Describe a hidden Markov model as hidden states, transition probabilities and emission distributions
- Read a state's expected stay from its stay probability
- Tell the most probable path apart from each step's state probabilities
- Choose the number of states with BIC and the stability of EM starts
Regimes that come back
ReadA change-point test looks for one or a few shifts in level. Some series instead switch back and forth between regimes: a machine idles and works, a geyser alternates short and long waits.
A hidden Markov modelHidden Markov modelA few hidden states follow a Markov chain; each state produces the observations from its own distribution. has three parts:
- Hidden states: K regimes you never observe directly.
- Transition probabilities: the chance of moving from state i to state j at the next step. The diagonal is the chance of staying.
- Emissions: each state produces the observations from its own distribution: a Gaussian, a Poisson rate or probabilities over categories.
The Baum–Welch algorithmBaum–Welch algorithmEM for a hidden Markov model: forward–backward gives each step's state probabilities, then the parameters are re-estimated. (EM for this model) fits it.
Old Faithful's waits
ReadThe waiting time between eruptions of Old Faithful has two clusters. Is there also a pattern in the order in which they occur?
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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
State 1 waits about 55.4 minutes and state 2 about 80.5. The transitions tell the story: after a short wait the chance of another short wait is only 0.07. Short waits are almost always followed by long ones.
How long a state lasts
ReadIf the stay probability is p, the number of steps a state lasts is geometric, with an expected stayExpected stay1 / (1 − stay probability): the average number of steps a state lasts once entered (a geometric duration). of 1 / (1 − p). A stay of 0.95 means about 20 steps; 0.5 means 2.
Here the long-wait state's expected stay is 1.72 eruptions. A geometric stay is a strong assumption: if real regimes have a typical length (shifts of 8 hours, say), the model splits or merges them.
One path, or a probability at each step?
ReadThe model gives two different answers to "which state was it in?":
- The most probable pathViterbi pathThe single most likely sequence of hidden states or labels given all the observations, found by dynamic programming. (Viterbi) is the single best sequence of states, drawn as segments in the first chart.
- The state probability at each stepState probability at a stepProbability of each hidden state at a step given the whole sequence (forward–backward). uses the whole sequence (forward–backward) and shows where the model is unsure.
A step on the path can belong to a state whose probability is only 0.55. Report the probabilities when the call matters.
Predict: a sticky state
PredictPredict first
A state's stay probability is 0.9. On average, how many steps does it last once entered?
Reveal
1 / (1 − 0.9) = 10 steps.
Counts at three sites
ReadCounts per step call for Poisson states, each with its own rate. With a sequence column, the three sites share the states, and each site starts from the initial probabilities.
A 2-state hidden Markov model with Poisson emissions for count (300 steps over 3 sequences): State 1 rate 1.931 (stay 16.2 steps); State 2 rate 9.085 (stay 9.94 steps). Log-likelihood -660.23, BIC 1349.0.
- Log-likelihood
- −660.23
- BIC
- 1348.98
- AIC
- 1330.46
Plots
View data
| state | t | count |
|---|---|---|
| State 2 | 1 | 6 |
| State 2 | 2 | 14 |
| State 2 | 3 | 9 |
| State 2 | 4 | 3 |
| State 2 | 5 | 7 |
| State 1 | 6 | 1 |
| State 1 | 7 | 3 |
| State 1 | 8 | 3 |
| State 2 | 9 | 9 |
| State 2 | 10 | 14 |
| State 2 | 11 | 7 |
| State 1 | 12 | 3 |
| State 1 | 13 | 0 |
| State 1 | 14 | 2 |
| State 1 | 15 | 2 |
| State 1 | 16 | 2 |
| State 1 | 17 | 2 |
| State 1 | 18 | 1 |
| State 1 | 19 | 4 |
| State 1 | 20 | 3 |
| State 1 | 21 | 1 |
| State 1 | 22 | 2 |
| State 1 | 23 | 1 |
| State 1 | 24 | 1 |
| State 1 | 25 | 3 |
| State 1 | 26 | 0 |
| State 1 | 27 | 2 |
| State 1 | 28 | 1 |
| State 1 | 29 | 3 |
| State 1 | 30 | 2 |
| State 1 | 31 | 2 |
| State 1 | 32 | 2 |
| State 1 | 33 | 2 |
| State 1 | 34 | 0 |
| State 1 | 35 | 1 |
| State 1 | 36 | 3 |
| State 2 | 37 | 11 |
| State 2 | 38 | 10 |
| State 2 | 39 | 9 |
| State 2 | 40 | 8 |
| State 2 | 41 | 5 |
| State 2 | 42 | 11 |
| State 2 | 43 | 14 |
| State 2 | 44 | 9 |
| State 2 | 45 | 6 |
| State 2 | 46 | 12 |
| State 2 | 47 | 8 |
| State 2 | 48 | 6 |
| State 2 | 49 | 7 |
| State 2 | 50 | 9 |
| State 2 | 51 | 11 |
| State 2 | 52 | 8 |
| State 2 | 53 | 6 |
| State 1 | 54 | 0 |
| State 1 | 55 | 2 |
| State 1 | 56 | 0 |
| State 1 | 57 | 2 |
| State 1 | 58 | 2 |
| State 1 | 59 | 1 |
| State 1 | 60 | 2 |
First 60 of 100 rows.
View data
| state | t | probability |
|---|---|---|
| State 1 | 1 | 1.211e-12 |
| State 2 | 1 | 1.0000 |
| State 1 | 2 | 3.942e-9 |
| State 2 | 2 | 1.0000 |
| State 1 | 3 | 0.0004 |
| State 2 | 3 | 0.9996 |
| State 1 | 4 | 0.2942 |
| State 2 | 4 | 0.7058 |
| State 1 | 5 | 0.2472 |
| State 2 | 5 | 0.7528 |
| State 1 | 6 | 0.9952 |
| State 2 | 6 | 0.0048 |
| State 1 | 7 | 0.9917 |
| State 2 | 7 | 0.0083 |
| State 1 | 8 | 0.9207 |
| State 2 | 8 | 0.0793 |
| State 1 | 9 | 0.0011 |
| State 2 | 9 | 0.9989 |
| State 1 | 10 | 1.812e-8 |
| State 2 | 10 | 1.0000 |
| State 1 | 11 | 0.0237 |
| State 2 | 11 | 0.9763 |
| State 1 | 12 | 0.9293 |
| State 2 | 12 | 0.0707 |
| State 1 | 13 | 0.9999 |
| State 2 | 13 | 5.900e-5 |
| State 1 | 14 | 0.9999 |
| State 2 | 14 | 0.0001 |
| State 1 | 15 | 0.9999 |
| State 2 | 15 | 0.0001 |
| State 1 | 16 | 0.9999 |
| State 2 | 16 | 0.0001 |
| State 1 | 17 | 0.9999 |
| State 2 | 17 | 0.0001 |
| State 1 | 18 | 1.0000 |
| State 2 | 18 | 3.664e-5 |
| State 1 | 19 | 0.9971 |
| State 2 | 19 | 0.0029 |
| State 1 | 20 | 0.9992 |
| State 2 | 20 | 0.0008 |
| State 1 | 21 | 1.0000 |
| State 2 | 21 | 2.911e-5 |
| State 1 | 22 | 0.9999 |
| State 2 | 22 | 0.0001 |
| State 1 | 23 | 1.0000 |
| State 2 | 23 | 2.643e-5 |
| State 1 | 24 | 1.0000 |
| State 2 | 24 | 2.801e-5 |
| State 1 | 25 | 0.9994 |
| State 2 | 25 | 0.0006 |
| State 1 | 26 | 1.0000 |
| State 2 | 26 | 6.030e-6 |
| State 1 | 27 | 0.9999 |
| State 2 | 27 | 0.0001 |
| State 1 | 28 | 1.0000 |
| State 2 | 28 | 2.840e-5 |
| State 1 | 29 | 0.9994 |
| State 2 | 29 | 0.0006 |
| State 1 | 30 | 0.9999 |
| State 2 | 30 | 0.0001 |
First 60 of 200 rows.
View data
| to | text | from | probability |
|---|---|---|---|
| State 1 | 0.94 | State 1 | 0.9383 |
| State 2 | 0.06 | State 1 | 0.0617 |
| State 1 | 0.10 | State 2 | 0.1006 |
| State 2 | 0.90 | State 2 | 0.8994 |
View data
| criterion name | states | criterion |
|---|---|---|
| AIC | 1 | 1941.00 |
| BIC | 1 | 1944.71 |
| AIC | 2 | 1330.46 |
| BIC | 2 | 1348.98 |
| AIC | 3 | 1341.81 |
| BIC | 3 | 1382.55 |
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 (-660.2281).
States
| State | Rate | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|
| State 1 | 1.931 | 1.498e-10 | 62.0% | 59.3% | 16.218 | 16.182 |
| State 2 | 9.085 | 1.0000 | 38.0% | 40.7% | 9.939 | 9.385 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.9383 | 0.0617 |
| State 2 | 0.1006 | 0.8994 |
Choosing the number of states
| States | Log-likelihood | Parameters | AIC | BIC | |
|---|---|---|---|---|---|
| 1 | −969.50 | 1 | 1941.00 | 1944.71 | |
| 2 | −660.23 | 5 | 1330.46 | 1348.98 | lowest BIC |
| 3 | −659.90 | 11 | 1341.81 | 1382.55 |
Most probable state of each step
| site | t | count | State | Probability of that state |
|---|---|---|---|---|
| A | 1 | 6 | State 2 | 1.0000 |
| A | 2 | 14 | State 2 | 1.0000 |
| A | 3 | 9 | State 2 | 0.9996 |
| A | 4 | 3 | State 2 | 0.7058 |
| A | 5 | 7 | State 2 | 0.7528 |
| A | 6 | 1 | State 1 | 0.9952 |
| A | 7 | 3 | State 1 | 0.9917 |
| A | 8 | 3 | State 1 | 0.9207 |
| A | 9 | 9 | State 2 | 0.9989 |
| A | 10 | 14 | State 2 | 1.0000 |
| A | 11 | 7 | State 2 | 0.9763 |
| A | 12 | 3 | State 1 | 0.9293 |
| A | 13 | 0 | State 1 | 0.9999 |
| A | 14 | 2 | State 1 | 0.9999 |
| A | 15 | 2 | State 1 | 0.9999 |
| A | 16 | 2 | State 1 | 0.9999 |
| A | 17 | 2 | State 1 | 0.9999 |
| A | 18 | 1 | State 1 | 1.0000 |
| A | 19 | 4 | State 1 | 0.9971 |
| A | 20 | 3 | State 1 | 0.9992 |
| A | 21 | 1 | State 1 | 1.0000 |
| A | 22 | 2 | State 1 | 0.9999 |
| A | 23 | 1 | State 1 | 1.0000 |
| A | 24 | 1 | State 1 | 1.0000 |
| A | 25 | 3 | State 1 | 0.9994 |
| A | 26 | 0 | State 1 | 1.0000 |
| A | 27 | 2 | State 1 | 0.9999 |
| A | 28 | 1 | State 1 | 1.0000 |
| A | 29 | 3 | State 1 | 0.9994 |
| A | 30 | 2 | State 1 | 0.9999 |
| A | 31 | 2 | State 1 | 0.9999 |
| A | 32 | 2 | State 1 | 0.9999 |
| A | 33 | 2 | State 1 | 0.9999 |
| A | 34 | 0 | State 1 | 1.0000 |
| A | 35 | 1 | State 1 | 0.9997 |
| A | 36 | 3 | State 1 | 0.9274 |
| A | 37 | 11 | State 2 | 1.0000 |
| A | 38 | 10 | State 2 | 1.0000 |
| A | 39 | 9 | State 2 | 1.0000 |
| A | 40 | 8 | State 2 | 0.9999 |
First 40 of 300 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 rate, 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.
The exact R script · R 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 e30a7635be493a3c
# Dataset: seq_hmm (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/seq_hmm.parquet", col_select = c("count", "site", "t")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = c("A", "B", "C")) # stored level order
df <- df[stats::complete.cases(df[c("count", "site", "t")]), , 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("count", "site", "t")) # 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 <- "count"
SEQUENCE <- "site"
TIME <- "t"
TEMPORAL <- FALSE
VALUE_CATEGORICAL <- FALSE
EMISSION <- "poisson"
K <- as.integer(2)
SHARED_VAR <- FALSE
STARTS <- as.integer(3)
SCAN <- TRUE
SCAN_MAX <- as.integer(3)
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
))
A 2-state hidden Markov model with Poisson emissions for count (300 steps over 3 sequences): State 1 rate 1.931 (stay 16.2 steps); State 2 rate 9.085 (stay 9.94 steps). Log-likelihood -660.23, BIC 1349.0.
- Log-likelihood
- −660.23
- BIC
- 1348.98
- AIC
- 1330.46
To keep this page light, the plots are shown once, under the R tab.
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 (-660.2281).
States
| State | Rate | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|
| State 1 | 1.931 | 1.498e-10 | 62.0% | 59.3% | 16.218 | 16.182 |
| State 2 | 9.085 | 1.0000 | 38.0% | 40.7% | 9.939 | 9.385 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.9383 | 0.0617 |
| State 2 | 0.1006 | 0.8994 |
Choosing the number of states
| States | Log-likelihood | Parameters | AIC | BIC | |
|---|---|---|---|---|---|
| 1 | −969.50 | 1 | 1941.00 | 1944.71 | |
| 2 | −660.23 | 5 | 1330.46 | 1348.98 | lowest BIC |
| 3 | −659.90 | 11 | 1341.81 | 1382.55 |
Most probable state of each step
| site | t | count | State | Probability of that state |
|---|---|---|---|---|
| A | 1 | 6 | State 2 | 1.0000 |
| A | 2 | 14 | State 2 | 1.0000 |
| A | 3 | 9 | State 2 | 0.9996 |
| A | 4 | 3 | State 2 | 0.7058 |
| A | 5 | 7 | State 2 | 0.7528 |
| A | 6 | 1 | State 1 | 0.9952 |
| A | 7 | 3 | State 1 | 0.9917 |
| A | 8 | 3 | State 1 | 0.9207 |
| A | 9 | 9 | State 2 | 0.9989 |
| A | 10 | 14 | State 2 | 1.0000 |
| A | 11 | 7 | State 2 | 0.9763 |
| A | 12 | 3 | State 1 | 0.9293 |
| A | 13 | 0 | State 1 | 0.9999 |
| A | 14 | 2 | State 1 | 0.9999 |
| A | 15 | 2 | State 1 | 0.9999 |
| A | 16 | 2 | State 1 | 0.9999 |
| A | 17 | 2 | State 1 | 0.9999 |
| A | 18 | 1 | State 1 | 1.0000 |
| A | 19 | 4 | State 1 | 0.9971 |
| A | 20 | 3 | State 1 | 0.9992 |
| A | 21 | 1 | State 1 | 1.0000 |
| A | 22 | 2 | State 1 | 0.9999 |
| A | 23 | 1 | State 1 | 1.0000 |
| A | 24 | 1 | State 1 | 1.0000 |
| A | 25 | 3 | State 1 | 0.9994 |
| A | 26 | 0 | State 1 | 1.0000 |
| A | 27 | 2 | State 1 | 0.9999 |
| A | 28 | 1 | State 1 | 1.0000 |
| A | 29 | 3 | State 1 | 0.9994 |
| A | 30 | 2 | State 1 | 0.9999 |
| A | 31 | 2 | State 1 | 0.9999 |
| A | 32 | 2 | State 1 | 0.9999 |
| A | 33 | 2 | State 1 | 0.9999 |
| A | 34 | 0 | State 1 | 1.0000 |
| A | 35 | 1 | State 1 | 0.9997 |
| A | 36 | 3 | State 1 | 0.9274 |
| A | 37 | 11 | State 2 | 1.0000 |
| A | 38 | 10 | State 2 | 1.0000 |
| A | 39 | 9 | State 2 | 1.0000 |
| A | 40 | 8 | State 2 | 0.9999 |
First 40 of 300 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 rate, 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.
The exact Python script · Python 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 e30a7635be493a3c
# Dataset: seq_hmm (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/seq_hmm.parquet", columns=["count", "site", "t"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=["A", "B", "C"]) # stored level order
df = df.dropna(subset=["count", "site", "t"]) # listwise deletion over the analysis columns
df["site"] = df["site"].cat.remove_unused_categories()
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, ["count", "site", "t"]) # 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 = "count"
SEQUENCE = "site"
TIME = "t"
TEMPORAL = False
VALUE_CATEGORICAL = False
EMISSION = "poisson"
K = int(2)
SHARED_VAR = False
STARTS = int(3)
SCAN = True
SCAN_MAX = int(3)
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 two rates are 1.93 and 9.09 per step. The comparison of 1 to 3 states favors 2 by BIC: the third state adds parameters but almost no log-likelihood.
Categories: customer journeys
ReadWith a categorical observation each state has its own probabilities over the values. Three states over the customer event log:
A 3-state hidden Markov model with categorical emissions for event (896 steps over 150 sequences): State 1 mostly view; State 2 mostly cart; State 3 mostly visit. Log-likelihood -1013.96, BIC 2184.3.
- Log-likelihood
- −1013.96
- BIC
- 2184.27
- AIC
- 2073.91
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 — 4 of 4 starts reached the best log-likelihood (-1013.9564).
States
| State | Most likely values | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|
| State 1 | view (0.46), search (0.35), support (0.18) | 0 | 54.2% | 64.3% | 3.931 | 3.200 |
| State 2 | cart (0.40), view (0.33), checkout (0.18) | 0 | 43.5% | 18.0% | 3.151 | 2.064 |
| State 3 | visit (1.00), support (0.00), checkout (0.00) | 1 | 2.3% | 17.7% | 1 | 1 |
Transition probabilities
| From | To State 1 | To State 2 | To State 3 |
|---|---|---|---|
| State 1 | 0.7456 | 0.2544 | 0 |
| State 2 | 0.2634 | 0.6826 | 0.0540 |
| State 3 | 1 | 1.402e-31 | 0 |
Emission probabilities
| State | visit | search | view | cart | checkout | support |
|---|---|---|---|---|---|---|
| State 1 | 1.421e-105 | 0.3548 | 0.4641 | 2.125e-12 | 5.591e-81 | 0.1811 |
| State 2 | 2.563e-34 | 1.385e-11 | 0.3328 | 0.4023 | 0.1808 | 0.0842 |
| State 3 | 1 | 3.082e-129 | 5.155e-129 | 2.663e-145 | 8.761e-101 | 1.558e-99 |
Most probable state of each step
| customer | minute | event | State | Probability of that state |
|---|---|---|---|---|
| C001 | 0 | visit | State 3 | 1 |
| C001 | 0 | view | State 1 | 1 |
| C001 | 2 | view | State 1 | 0.6037 |
| C001 | 3 | cart | State 2 | 1.0000 |
| C001 | 13 | checkout | State 2 | 1 |
| C001 | 15 | view | State 1 | 0.5301 |
| C001 | 15 | support | State 1 | 0.8316 |
| C001 | 16 | search | State 1 | 1.0000 |
| C001 | 18 | search | State 1 | 1.0000 |
| C002 | 0 | visit | State 3 | 1 |
| C002 | 5 | view | State 1 | 1 |
| C002 | 7 | view | State 1 | 0.8643 |
| C002 | 17 | view | State 1 | 0.8227 |
| C002 | 18 | support | State 1 | 0.8414 |
| C002 | 18 | support | State 1 | 0.7981 |
| C003 | 0 | visit | State 3 | 1 |
| C003 | 5 | view | State 1 | 1 |
| C003 | 6 | view | State 1 | 0.9204 |
| C003 | 6 | search | State 1 | 1.0000 |
| C003 | 6 | search | State 1 | 1.0000 |
| C003 | 8 | view | State 1 | 0.8344 |
| C003 | 10 | view | State 1 | 0.7283 |
| C004 | 0 | visit | State 3 | 1 |
| C004 | 2 | search | State 1 | 1 |
| C004 | 2 | view | State 1 | 0.8034 |
| C005 | 0 | visit | State 3 | 1 |
| C005 | 0 | search | State 1 | 1 |
| C005 | 1 | view | State 1 | 0.6037 |
| C005 | 1 | cart | State 2 | 1.0000 |
| C005 | 3 | view | State 1 | 0.6037 |
| C005 | 4 | search | State 1 | 1.0000 |
| C005 | 5 | view | State 1 | 0.8034 |
| C006 | 0 | visit | State 3 | 1 |
| C006 | 10 | view | State 1 | 1 |
| C006 | 11 | cart | State 2 | 1.0000 |
| C006 | 13 | checkout | State 2 | 1 |
| C006 | 13 | support | State 2 | 0.7638 |
| C006 | 18 | cart | State 2 | 1.0000 |
| C006 | 20 | support | State 1 | 0.7015 |
| C006 | 21 | search | State 1 | 1.0000 |
First 40 of 50 rows.
- 141 rows repeat a time within their sequence; they are kept in row order, one step each.
- EM (Baum–Welch) from 4 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 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.
The exact R script · R 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 47a39213993e7e73
# Dataset: ds1_events (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/ds1_events.parquet", col_select = c("event", "customer", "minute")))
n_input <- nrow(df)
df[["event"]] <- factor(df[["event"]], levels = c("visit", "search", "view", "cart", "checkout", "support")) # stored level order
df[["customer"]] <- factor(df[["customer"]], levels = sort(unique(df[["customer"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("event", "customer", "minute")]), , 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("event", "customer", "minute")) # 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 <- "event"
SEQUENCE <- "customer"
TIME <- "minute"
TEMPORAL <- FALSE
VALUE_CATEGORICAL <- TRUE
EMISSION <- "auto"
K <- as.integer(3)
SHARED_VAR <- FALSE
STARTS <- as.integer(4)
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
))
A 3-state hidden Markov model with categorical emissions for event (896 steps over 150 sequences): State 1 mostly view; State 2 mostly cart; State 3 mostly visit. Log-likelihood -1013.96, BIC 2184.3.
- Log-likelihood
- −1013.96
- BIC
- 2184.27
- AIC
- 2073.91
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 — 4 of 4 starts reached the best log-likelihood (-1013.9564).
States
| State | Most likely values | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|
| State 1 | view (0.46), search (0.35), support (0.18) | 0 | 54.2% | 64.3% | 3.931 | 3.200 |
| State 2 | cart (0.40), view (0.33), checkout (0.18) | 0 | 43.5% | 18.0% | 3.151 | 2.064 |
| State 3 | visit (1.00), support (0.00), checkout (0.00) | 1 | 2.3% | 17.7% | 1 | 1 |
Transition probabilities
| From | To State 1 | To State 2 | To State 3 |
|---|---|---|---|
| State 1 | 0.7456 | 0.2544 | 0 |
| State 2 | 0.2634 | 0.6826 | 0.0540 |
| State 3 | 1 | 1.402e-31 | 0 |
Emission probabilities
| State | visit | search | view | cart | checkout | support |
|---|---|---|---|---|---|---|
| State 1 | 1.421e-105 | 0.3548 | 0.4641 | 2.125e-12 | 5.591e-81 | 0.1811 |
| State 2 | 2.563e-34 | 1.385e-11 | 0.3328 | 0.4023 | 0.1808 | 0.0842 |
| State 3 | 1 | 3.082e-129 | 5.155e-129 | 2.663e-145 | 8.761e-101 | 1.558e-99 |
Most probable state of each step
| customer | minute | event | State | Probability of that state |
|---|---|---|---|---|
| C001 | 0 | visit | State 3 | 1.0000 |
| C001 | 0 | view | State 1 | 1.0000 |
| C001 | 2 | view | State 1 | 0.6037 |
| C001 | 3 | cart | State 2 | 1.0000 |
| C001 | 13 | checkout | State 2 | 1.0000 |
| C001 | 15 | view | State 1 | 0.5301 |
| C001 | 15 | support | State 1 | 0.8316 |
| C001 | 16 | search | State 1 | 1.0000 |
| C001 | 18 | search | State 1 | 1.0000 |
| C002 | 0 | visit | State 3 | 1.0000 |
| C002 | 5 | view | State 1 | 1.0000 |
| C002 | 7 | view | State 1 | 0.8643 |
| C002 | 17 | view | State 1 | 0.8227 |
| C002 | 18 | support | State 1 | 0.8414 |
| C002 | 18 | support | State 1 | 0.7981 |
| C003 | 0 | visit | State 3 | 1.000 |
| C003 | 5 | view | State 1 | 1.000 |
| C003 | 6 | view | State 1 | 0.9204 |
| C003 | 6 | search | State 1 | 1.0000 |
| C003 | 6 | search | State 1 | 1.0000 |
| C003 | 8 | view | State 1 | 0.8344 |
| C003 | 10 | view | State 1 | 0.7283 |
| C004 | 0 | visit | State 3 | 1 |
| C004 | 2 | search | State 1 | 1 |
| C004 | 2 | view | State 1 | 0.8034 |
| C005 | 0 | visit | State 3 | 1.000 |
| C005 | 0 | search | State 1 | 1.000 |
| C005 | 1 | view | State 1 | 0.6037 |
| C005 | 1 | cart | State 2 | 1.0000 |
| C005 | 3 | view | State 1 | 0.6037 |
| C005 | 4 | search | State 1 | 1.0000 |
| C005 | 5 | view | State 1 | 0.8034 |
| C006 | 0 | visit | State 3 | 1.0000 |
| C006 | 10 | view | State 1 | 1.0000 |
| C006 | 11 | cart | State 2 | 1.0000 |
| C006 | 13 | checkout | State 2 | 1.0000 |
| C006 | 13 | support | State 2 | 0.7638 |
| C006 | 18 | cart | State 2 | 1.0000 |
| C006 | 20 | support | State 1 | 0.7015 |
| C006 | 21 | search | State 1 | 1.0000 |
First 40 of 50 rows.
- 141 rows repeat a time within their sequence; they are kept in row order, one step each.
- EM (Baum–Welch) from 4 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 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.
The exact Python script · Python 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 47a39213993e7e73
# Dataset: ds1_events (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/ds1_events.parquet", columns=["event", "customer", "minute"])
n_input = len(df)
df["event"] = pd.Categorical(df["event"], categories=["visit", "search", "view", "cart", "checkout", "support"]) # stored level order
df["customer"] = pd.Categorical(df["customer"], categories=sorted(df["customer"].dropna().unique()))
df = df.dropna(subset=["event", "customer", "minute"]) # listwise deletion over the analysis columns
df["event"] = df["event"].cat.remove_unused_categories()
df["customer"] = df["customer"].cat.remove_unused_categories()
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, ["event", "customer", "minute"]) # 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 = "event"
SEQUENCE = "customer"
TIME = "minute"
TEMPORAL = False
VALUE_CATEGORICAL = True
EMISSION = "auto"
K = int(3)
SHARED_VAR = False
STARTS = int(4)
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,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; a table cut from 896 to 50 rows; 2 chart(s) dropped to stay under 100 KB; a table cut from 896 to 50 rows.
Read each state by its most likely events in the States table: a browsing state, a buying state and a support state is the kind of story to look for. The numbers 1, 2 and 3 carry no meaning of their own. CodeSplash orders the states so the labels don't switch between runs.
How many states?
ReadEM climbs to a local optimum, so CodeSplash fits from several starts and keeps the best. The "Same optimum from different starts" check says how many starts agree.
A 3-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 54.24 (stay 1.07 steps); State 2 mean 76.56 (stay 3.2 steps); State 3 mean 82.76 (stay 1.23 steps). Log-likelihood -986.86, BIC 2052.2.
- Log-likelihood
- −986.86
- BIC
- 2052.21
- AIC
- 2001.72
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 — 2 of 3 starts reached the best log-likelihood (-986.8623).
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 | 54.236 | 5.603 | 0 | 34.8% | 34.6% | 1.071 | 1.068 |
| State 2 | 76.565 | 5.627 | 8.109e-71 | 31.5% | 30.5% | 3.204 | 4.882 |
| State 3 | 82.756 | 5.083 | 1.0000 | 33.7% | 34.9% | 1.228 | 1.284 |
Transition probabilities
| From | To State 1 | To State 2 | To State 3 |
|---|---|---|---|
| State 1 | 0.0665 | 0.2239 | 0.7095 |
| State 2 | 0.2253 | 0.6879 | 0.0867 |
| State 3 | 0.7538 | 0.0604 | 0.1858 |
Choosing the number of states
| States | Log-likelihood | Parameters | AIC | BIC | |
|---|---|---|---|---|---|
| 1 | −1095.29 | 2 | 2194.58 | 2201.79 | |
| 2 | −997.22 | 7 | 2008.44 | 2033.68 | lowest BIC |
| 3 | −986.86 | 14 | 2001.72 | 2052.21 | |
| 4 | −975.32 | 23 | 1996.64 | 2079.58 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 3 | 1 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 3 | 0.7364 |
| 4 | 62 | State 1 | 0.9843 |
| 5 | 85 | State 3 | 0.9640 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 3 | 0.9530 |
| 8 | 85 | State 3 | 0.9505 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 3 | 0.9703 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 3 | 0.8242 |
| 13 | 78 | State 3 | 0.7701 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 3 | 0.9575 |
| 16 | 52 | State 1 | 0.9999 |
| 17 | 62 | State 1 | 0.9333 |
| 18 | 84 | State 3 | 0.9358 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 3 | 0.9074 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.7535 |
| 24 | 69 | State 2 | 0.8933 |
| 25 | 74 | State 2 | 0.9139 |
| 26 | 83 | State 2 | 0.4867 |
| 27 | 55 | State 1 | 0.9974 |
| 28 | 76 | State 2 | 0.8633 |
| 29 | 78 | State 2 | 0.9635 |
| 30 | 79 | State 2 | 0.9809 |
| 31 | 73 | State 2 | 0.9926 |
| 32 | 77 | State 2 | 0.9621 |
| 33 | 66 | State 2 | 0.8501 |
| 34 | 80 | State 2 | 0.8852 |
| 35 | 74 | State 2 | 0.8216 |
| 36 | 52 | State 1 | 0.9993 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 3 | 0.9236 |
| 39 | 59 | State 1 | 0.9990 |
| 40 | 90 | State 3 | 0.9428 |
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.
The exact R script · R 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 678adecf45355eb0
# 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(3)
SHARED_VAR <- FALSE
STARTS <- as.integer(3)
SCAN <- TRUE
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
))
A 3-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 54.24 (stay 1.07 steps); State 2 mean 76.56 (stay 3.2 steps); State 3 mean 82.76 (stay 1.23 steps). Log-likelihood -986.86, BIC 2052.2.
- Log-likelihood
- −986.86
- BIC
- 2052.21
- AIC
- 2001.72
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 — 2 of 3 starts reached the best log-likelihood (-986.8623).
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 | 54.236 | 5.603 | 0 | 34.8% | 34.6% | 1.071 | 1.068 |
| State 2 | 76.565 | 5.627 | 8.109e-71 | 31.5% | 30.5% | 3.204 | 4.882 |
| State 3 | 82.756 | 5.083 | 1.0000 | 33.7% | 34.9% | 1.228 | 1.284 |
Transition probabilities
| From | To State 1 | To State 2 | To State 3 |
|---|---|---|---|
| State 1 | 0.0665 | 0.2239 | 0.7095 |
| State 2 | 0.2253 | 0.6879 | 0.0867 |
| State 3 | 0.7538 | 0.0604 | 0.1858 |
Choosing the number of states
| States | Log-likelihood | Parameters | AIC | BIC | |
|---|---|---|---|---|---|
| 1 | −1095.29 | 2 | 2194.58 | 2201.79 | |
| 2 | −997.22 | 7 | 2008.44 | 2033.68 | lowest BIC |
| 3 | −986.86 | 14 | 2001.72 | 2052.21 | |
| 4 | −975.32 | 23 | 1996.64 | 2079.58 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 3 | 1.000 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 3 | 0.7364 |
| 4 | 62 | State 1 | 0.9843 |
| 5 | 85 | State 3 | 0.9640 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 3 | 0.9530 |
| 8 | 85 | State 3 | 0.9505 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 3 | 0.9703 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 3 | 0.8242 |
| 13 | 78 | State 3 | 0.7701 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 3 | 0.9575 |
| 16 | 52 | State 1 | 0.9999 |
| 17 | 62 | State 1 | 0.9333 |
| 18 | 84 | State 3 | 0.9358 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 3 | 0.9074 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.7535 |
| 24 | 69 | State 2 | 0.8933 |
| 25 | 74 | State 2 | 0.9139 |
| 26 | 83 | State 2 | 0.4867 |
| 27 | 55 | State 1 | 0.9974 |
| 28 | 76 | State 2 | 0.8633 |
| 29 | 78 | State 2 | 0.9635 |
| 30 | 79 | State 2 | 0.9809 |
| 31 | 73 | State 2 | 0.9926 |
| 32 | 77 | State 2 | 0.9621 |
| 33 | 66 | State 2 | 0.8501 |
| 34 | 80 | State 2 | 0.8852 |
| 35 | 74 | State 2 | 0.8216 |
| 36 | 52 | State 1 | 0.9993 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 3 | 0.9236 |
| 39 | 59 | State 1 | 0.9990 |
| 40 | 90 | State 3 | 0.9428 |
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.
The exact Python script · Python 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 678adecf45355eb0
# 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(3)
SHARED_VAR = False
STARTS = int(3)
SCAN = True
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,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
With three states the log-likelihood improves, and the scan shows whether BICAIC and BIC for a hidden Markov model−2 log-likelihood plus 2 (AIC) or log n (BIC) per free parameter; lower is better when comparing numbers of states. thinks it's worth the extra parameters. It favors 2 states here. Prefer a number of states whose regimes you can name and that stays stable across starts.
Check: hidden Markov models
CheckpointCheck yourself
Which parts does a hidden Markov model estimate?
Show the answer
Answer: a
Hidden states follow a Markov chain (transitions), and each state produces the observations from its own distribution (emissions).
Check yourself
A state's stay probability is 0.95. What is its expected stay in steps?
Show the answer
Answer: 20
1 / (1 − 0.95) = 20.
Check yourself
At one step the most probable path says state 2, but the state probabilities are 0.52 for state 2 and 0.48 for state 1. What should you report?
Show the answer
Answer: a
The path is a single best guess; the probabilities show how sure the model is at each step.
Check yourself
Only one of five EM starts reached the best log-likelihood. What does that suggest?
Show the answer
Answer: a
Starts that reach the same best fit are a sign the optimum is stable; disagreement means more starts are needed.
Concepts in this lesson