Skip to content

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.

Advanced ~16 min9 steps

What runs in CodeSplash

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

Read first

01

Regimes that come back

Read

A 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.

02

Old Faithful's waits

Read

The waiting time between eruptions of Old Faithful has two clusters. Is there also a pattern in the order in which they occur?

Hidden Markov modelRecorded · Python and R agreeRecorded 2026-11-21 · 33 values compared
R

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

StateMeanSDInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 155.4366.6096.777e-8238.5%38.2%1.0751.072
State 280.5275.478161.5%61.8%1.7161.714

Transition probabilities

FromTo State 1To State 2
State 10.06980.9302
State 20.58280.4172

Most probable state of each step

StepwaitingStateProbability of that state
179State 21
254State 11.0000
374State 20.9997
462State 10.9979
585State 21.0000
655State 11.0000
788State 21.0000
885State 21.0000
951State 11.0000
1085State 21.0000
1154State 11.0000
1284State 21.0000
1378State 20.9995
1447State 11.0000
1583State 21.0000
1652State 11.0000
1762State 10.9626
1884State 21.0000
1952State 11.0000
2079State 21.0000
2151State 11.0000
2247State 11.0000
2378State 20.9999
2469State 10.7240
2574State 20.9706
2683State 21.0000
2755State 11.0000
2876State 20.9985
2978State 20.9917
3079State 20.9961
3173State 20.8381
3277State 20.9988
3366State 10.9598
3480State 20.9998
3574State 20.9946
3652State 11.0000
3748State 11.0000
3880State 21.0000
3959State 10.9998
4090State 21.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
))
Python

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

StateMeanSDInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 155.4366.6096.777e-8238.5%38.2%1.0751.072
State 280.5275.4781.000061.5%61.8%1.7161.714

Transition probabilities

FromTo State 1To State 2
State 10.06980.9302
State 20.58280.4172

Most probable state of each step

StepwaitingStateProbability of that state
179State 21.000
254State 11.0000
374State 20.9997
462State 10.9979
585State 21.0000
655State 11.0000
788State 21.0000
885State 21.0000
951State 11.0000
1085State 21.0000
1154State 11.0000
1284State 21.0000
1378State 20.9995
1447State 11.0000
1583State 21.0000
1652State 11.0000
1762State 10.9626
1884State 21.0000
1952State 11.0000
2079State 21.0000
2151State 11.0000
2247State 11.0000
2378State 20.9999
2469State 10.7240
2574State 20.9706
2683State 21.0000
2755State 11.0000
2876State 20.9985
2978State 20.9917
3079State 20.9961
3173State 20.8381
3277State 20.9988
3366State 10.9598
3480State 20.9998
3574State 20.9946
3652State 11.0000
3748State 11.0000
3880State 21.0000
3959State 10.9998
4090State 21.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.

03

How long a state lasts

Read

If 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.

04

One path, or a probability at each step?

Read

The 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.

05

Predict: a sticky state

Predict

Predict first

A state's stay probability is 0.9. On average, how many steps does it last once entered?

About 2 stepsAbout 10 stepsAbout 100 steps
Reveal

1 / (1 − 0.9) = 10 steps.

06

Counts at three sites

Read

Counts 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.

Hidden Markov modelRecorded · Python and R agreeRecorded 2026-11-21 · 41 values compared
R

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

count with the most probable states (site A)Where does the level of the series change, and what is the level in each segment?
View data
statetcount
State 216
State 2214
State 239
State 243
State 257
State 161
State 173
State 183
State 299
State 21014
State 2117
State 1123
State 1130
State 1142
State 1152
State 1162
State 1172
State 1181
State 1194
State 1203
State 1211
State 1222
State 1231
State 1241
State 1253
State 1260
State 1272
State 1281
State 1293
State 1302
State 1312
State 1322
State 1332
State 1340
State 1351
State 1363
State 23711
State 23810
State 2399
State 2408
State 2415
State 24211
State 24314
State 2449
State 2456
State 24612
State 2478
State 2486
State 2497
State 2509
State 25111
State 2528
State 2536
State 1540
State 1552
State 1560
State 1572
State 1582
State 1591
State 1602

First 60 of 100 rows.

Probability of each state over time (site A)How does the series move over time, and where is an estimated break?
View data
statetprobability
State 111.211e-12
State 211.0000
State 123.942e-9
State 221.0000
State 130.0004
State 230.9996
State 140.2942
State 240.7058
State 150.2472
State 250.7528
State 160.9952
State 260.0048
State 170.9917
State 270.0083
State 180.9207
State 280.0793
State 190.0011
State 290.9989
State 1101.812e-8
State 2101.0000
State 1110.0237
State 2110.9763
State 1120.9293
State 2120.0707
State 1130.9999
State 2135.900e-5
State 1140.9999
State 2140.0001
State 1150.9999
State 2150.0001
State 1160.9999
State 2160.0001
State 1170.9999
State 2170.0001
State 1181.0000
State 2183.664e-5
State 1190.9971
State 2190.0029
State 1200.9992
State 2200.0008
State 1211.0000
State 2212.911e-5
State 1220.9999
State 2220.0001
State 1231.0000
State 2232.643e-5
State 1241.0000
State 2242.801e-5
State 1250.9994
State 2250.0006
State 1261.0000
State 2266.030e-6
State 1270.9999
State 2270.0001
State 1281.0000
State 2282.840e-5
State 1290.9994
State 2290.0006
State 1300.9999
State 2300.0001

First 60 of 200 rows.

Transition probabilities (row = from, column = to)What do the values of a square or rectangular result matrix look like at a glance?
View data
totextfromprobability
State 10.94State 10.9383
State 20.06State 10.0617
State 10.10State 20.1006
State 20.90State 20.8994
Information criteria by number of states (lower is better)How does the series move over time, and where is an estimated break?
View data
criterion namestatescriterion
AIC11941.00
BIC11944.71
AIC21330.46
BIC21348.98
AIC31341.81
BIC31382.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

StateRateInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 11.9311.498e-1062.0%59.3%16.21816.182
State 29.0851.000038.0%40.7%9.9399.385

Transition probabilities

FromTo State 1To State 2
State 10.93830.0617
State 20.10060.8994

Choosing the number of states

StatesLog-likelihoodParametersAICBIC
1−969.5011941.001944.71
2−660.2351330.461348.98lowest BIC
3−659.90111341.811382.55

Most probable state of each step

sitetcountStateProbability of that state
A16State 21.0000
A214State 21.0000
A39State 20.9996
A43State 20.7058
A57State 20.7528
A61State 10.9952
A73State 10.9917
A83State 10.9207
A99State 20.9989
A1014State 21.0000
A117State 20.9763
A123State 10.9293
A130State 10.9999
A142State 10.9999
A152State 10.9999
A162State 10.9999
A172State 10.9999
A181State 11.0000
A194State 10.9971
A203State 10.9992
A211State 11.0000
A222State 10.9999
A231State 11.0000
A241State 11.0000
A253State 10.9994
A260State 11.0000
A272State 10.9999
A281State 11.0000
A293State 10.9994
A302State 10.9999
A312State 10.9999
A322State 10.9999
A332State 10.9999
A340State 11.0000
A351State 10.9997
A363State 10.9274
A3711State 21.0000
A3810State 21.0000
A399State 21.0000
A408State 20.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
))
Python

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

StateRateInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 11.9311.498e-1062.0%59.3%16.21816.182
State 29.0851.000038.0%40.7%9.9399.385

Transition probabilities

FromTo State 1To State 2
State 10.93830.0617
State 20.10060.8994

Choosing the number of states

StatesLog-likelihoodParametersAICBIC
1−969.5011941.001944.71
2−660.2351330.461348.98lowest BIC
3−659.90111341.811382.55

Most probable state of each step

sitetcountStateProbability of that state
A16State 21.0000
A214State 21.0000
A39State 20.9996
A43State 20.7058
A57State 20.7528
A61State 10.9952
A73State 10.9917
A83State 10.9207
A99State 20.9989
A1014State 21.0000
A117State 20.9763
A123State 10.9293
A130State 10.9999
A142State 10.9999
A152State 10.9999
A162State 10.9999
A172State 10.9999
A181State 11.0000
A194State 10.9971
A203State 10.9992
A211State 11.0000
A222State 10.9999
A231State 11.0000
A241State 11.0000
A253State 10.9994
A260State 11.0000
A272State 10.9999
A281State 11.0000
A293State 10.9994
A302State 10.9999
A312State 10.9999
A322State 10.9999
A332State 10.9999
A340State 11.0000
A351State 10.9997
A363State 10.9274
A3711State 21.0000
A3810State 21.0000
A399State 21.0000
A408State 20.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.

07

Categories: customer journeys

Read

With a categorical observation each state has its own probabilities over the values. Three states over the customer event log:

Hidden Markov modelRecorded · Python and R agreeRecorded 2026-11-21 · 57 values compared
R

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

StateMost likely valuesInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 1view (0.46), search (0.35), support (0.18)054.2%64.3%3.9313.200
State 2cart (0.40), view (0.33), checkout (0.18)043.5%18.0%3.1512.064
State 3visit (1.00), support (0.00), checkout (0.00)12.3%17.7%11

Transition probabilities

FromTo State 1To State 2To State 3
State 10.74560.25440
State 20.26340.68260.0540
State 311.402e-310

Emission probabilities

Statevisitsearchviewcartcheckoutsupport
State 11.421e-1050.35480.46412.125e-125.591e-810.1811
State 22.563e-341.385e-110.33280.40230.18080.0842
State 313.082e-1295.155e-1292.663e-1458.761e-1011.558e-99

Most probable state of each step

customerminuteeventStateProbability of that state
C0010visitState 31
C0010viewState 11
C0012viewState 10.6037
C0013cartState 21.0000
C00113checkoutState 21
C00115viewState 10.5301
C00115supportState 10.8316
C00116searchState 11.0000
C00118searchState 11.0000
C0020visitState 31
C0025viewState 11
C0027viewState 10.8643
C00217viewState 10.8227
C00218supportState 10.8414
C00218supportState 10.7981
C0030visitState 31
C0035viewState 11
C0036viewState 10.9204
C0036searchState 11.0000
C0036searchState 11.0000
C0038viewState 10.8344
C00310viewState 10.7283
C0040visitState 31
C0042searchState 11
C0042viewState 10.8034
C0050visitState 31
C0050searchState 11
C0051viewState 10.6037
C0051cartState 21.0000
C0053viewState 10.6037
C0054searchState 11.0000
C0055viewState 10.8034
C0060visitState 31
C00610viewState 11
C00611cartState 21.0000
C00613checkoutState 21
C00613supportState 20.7638
C00618cartState 21.0000
C00620supportState 10.7015
C00621searchState 11.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
))
Python

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

StateMost likely valuesInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 1view (0.46), search (0.35), support (0.18)054.2%64.3%3.9313.200
State 2cart (0.40), view (0.33), checkout (0.18)043.5%18.0%3.1512.064
State 3visit (1.00), support (0.00), checkout (0.00)12.3%17.7%11

Transition probabilities

FromTo State 1To State 2To State 3
State 10.74560.25440
State 20.26340.68260.0540
State 311.402e-310

Emission probabilities

Statevisitsearchviewcartcheckoutsupport
State 11.421e-1050.35480.46412.125e-125.591e-810.1811
State 22.563e-341.385e-110.33280.40230.18080.0842
State 313.082e-1295.155e-1292.663e-1458.761e-1011.558e-99

Most probable state of each step

customerminuteeventStateProbability of that state
C0010visitState 31.0000
C0010viewState 11.0000
C0012viewState 10.6037
C0013cartState 21.0000
C00113checkoutState 21.0000
C00115viewState 10.5301
C00115supportState 10.8316
C00116searchState 11.0000
C00118searchState 11.0000
C0020visitState 31.0000
C0025viewState 11.0000
C0027viewState 10.8643
C00217viewState 10.8227
C00218supportState 10.8414
C00218supportState 10.7981
C0030visitState 31.000
C0035viewState 11.000
C0036viewState 10.9204
C0036searchState 11.0000
C0036searchState 11.0000
C0038viewState 10.8344
C00310viewState 10.7283
C0040visitState 31
C0042searchState 11
C0042viewState 10.8034
C0050visitState 31.000
C0050searchState 11.000
C0051viewState 10.6037
C0051cartState 21.0000
C0053viewState 10.6037
C0054searchState 11.0000
C0055viewState 10.8034
C0060visitState 31.0000
C00610viewState 11.0000
C00611cartState 21.0000
C00613checkoutState 21.0000
C00613supportState 20.7638
C00618cartState 21.0000
C00620supportState 10.7015
C00621searchState 11.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.

08

How many states?

Read

EM 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.

Hidden Markov modelRecorded · Python and R agreeRecorded 2026-11-21 · 58 values compared
R

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

StateMeanSDInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 154.2365.603034.8%34.6%1.0711.068
State 276.5655.6278.109e-7131.5%30.5%3.2044.882
State 382.7565.0831.000033.7%34.9%1.2281.284

Transition probabilities

FromTo State 1To State 2To State 3
State 10.06650.22390.7095
State 20.22530.68790.0867
State 30.75380.06040.1858

Choosing the number of states

StatesLog-likelihoodParametersAICBIC
1−1095.2922194.582201.79
2−997.2272008.442033.68lowest BIC
3−986.86142001.722052.21
4−975.32231996.642079.58

Most probable state of each step

StepwaitingStateProbability of that state
179State 31
254State 11.0000
374State 30.7364
462State 10.9843
585State 30.9640
655State 11.0000
788State 30.9530
885State 30.9505
951State 11.0000
1085State 30.9703
1154State 11.0000
1284State 30.8242
1378State 30.7701
1447State 11.0000
1583State 30.9575
1652State 10.9999
1762State 10.9333
1884State 30.9358
1952State 11.0000
2079State 30.9074
2151State 11.0000
2247State 11.0000
2378State 20.7535
2469State 20.8933
2574State 20.9139
2683State 20.4867
2755State 10.9974
2876State 20.8633
2978State 20.9635
3079State 20.9809
3173State 20.9926
3277State 20.9621
3366State 20.8501
3480State 20.8852
3574State 20.8216
3652State 10.9993
3748State 11.0000
3880State 30.9236
3959State 10.9990
4090State 30.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
))
Python

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

StateMeanSDInitial probabilityLong-run shareShare of steps (most probable path)Expected stay (steps)Mean run in path (steps)
State 154.2365.603034.8%34.6%1.0711.068
State 276.5655.6278.109e-7131.5%30.5%3.2044.882
State 382.7565.0831.000033.7%34.9%1.2281.284

Transition probabilities

FromTo State 1To State 2To State 3
State 10.06650.22390.7095
State 20.22530.68790.0867
State 30.75380.06040.1858

Choosing the number of states

StatesLog-likelihoodParametersAICBIC
1−1095.2922194.582201.79
2−997.2272008.442033.68lowest BIC
3−986.86142001.722052.21
4−975.32231996.642079.58

Most probable state of each step

StepwaitingStateProbability of that state
179State 31.000
254State 11.0000
374State 30.7364
462State 10.9843
585State 30.9640
655State 11.0000
788State 30.9530
885State 30.9505
951State 11.0000
1085State 30.9703
1154State 11.0000
1284State 30.8242
1378State 30.7701
1447State 11.0000
1583State 30.9575
1652State 10.9999
1762State 10.9333
1884State 30.9358
1952State 11.0000
2079State 30.9074
2151State 11.0000
2247State 11.0000
2378State 20.7535
2469State 20.8933
2574State 20.9139
2683State 20.4867
2755State 10.9974
2876State 20.8633
2978State 20.9635
3079State 20.9809
3173State 20.9926
3277State 20.9621
3366State 20.8501
3480State 20.8852
3574State 20.8216
3652State 10.9993
3748State 11.0000
3880State 30.9236
3959State 10.9990
4090State 30.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.

09

Check: hidden Markov models

Checkpoint

Check 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