Skip to content

Hidden states and mixed roles: HMMs and mixed-membership blockmodels

Two discrete latent representations. A hidden Markov model summarizes a sequence as a walk through a few unseen states; a mixed-membership blockmodel gives each node of a network a blend of roles.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Write an HMM's joint probability, compute a forward-algorithm likelihood, and read transitions and stays
  • Explain the geometric-duration assumption, label switching and why HMMs need several starts
  • Describe the mixed-membership blockmodel's link probability and contrast it with one-block-per-node models

Read first

01

A sequence driven by unseen states

Read

A hidden Markov modelHidden Markov modelA few hidden states follow a Markov chain; each state produces the observations from its own distribution. says a sequence moves through KK hidden states. Each step, the state may switch according to a transition matrix AA, and the observation is drawn from that state's emission distribution bkb_k:

p(z1:T,x1:T)=πz1 bz1(x1)∏t=2TAzt−1zt bzt(xt).p(z_{1:T}, x_{1:T}) = \pi_{z_1}\, b_{z_1}(x_1) \prod_{t=2}^{T} A_{z_{t-1} z_t}\, b_{z_t}(x_t) .

The representation of a sequence is its path of states: a few regimes instead of hundreds of raw values.

02

The forward algorithm

Read

The likelihood sums over every possible state path, but the forward algorithm does it in O(TK2)O(TK^2): carry a vector αt\alpha_t of "probability so far, ending in each state", and update

αt=(αt−1A)⊙b(xt).\alpha_t = (\alpha_{t-1} A) \odot b(x_t).

The reference's example uses two states and four observations; the likelihood is 0.0389. Real sequences multiply hundreds of small numbers, so implementations rescale each step or work in logs. Baum–Welch (EM) refits AA and bb from forward–backward probabilities.

03

Old Faithful's waiting times

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

Two states describe the geyser's waiting times: one around 55.4 minutes and one around 80.5. A short wait is followed by a long one with probability 0.93: the states alternate rather than persist.

Scanning 1 to 4 states, BIC picks 2, while AIC keeps improving with more.

04

Stays and long-run shares

Explore

The hidden part of an HMM is a Markov chain. Set P(stay in A) and P(stay in B) and watch the simulated path.

AExplorable · A Markov chain playground

When tomorrow depends only on today, where does a process settle in the long run?

In the long run, what share of time does the chain spend in A?

0.50
How sure?
0.80
0.60
500
long-run 0.67

The strip shows the first steps: state A in one color, B in the other. Long runs of one color mean a sticky chain.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Raise P(stay in A) toward 1: stays in A grow like 1/(1−p)1/(1 - p) and the long-run share of A climbs. Lower both stays below a half and the chain flips almost every step, like the geyser's alternating waits.

05

What an HMM assumes

Read
  • Geometric stays. A state lasts 1/(1−Akk)1/(1 - A_{kk}) steps on average, and short stays are always likeliest. Regimes with a typical length need a semi-Markov model.
  • Label switching. State 1 in one fit can be state 2 in another; sort or match states by their emission means before comparing.
  • Local optima. EM can stop at a poor fit. CodeSplash runs several starts and reports how many reached the best one.
06

Networks: one role, or a mix?

Read

A stochastic blockmodelStochastic blockmodelA network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks. puts every node in one block; the chance of a link depends only on the two blocks. That is good for communities and for core–periphery structure.

Stochastic blockmodelRecorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

The stochastic blockmodel puts 49 nodes in 2 blocks (chosen by BIC); the average node sits in its block with probability 1.000.

Blocks
2
ICL
−348.54
Mean certainty
1.0000

Plots

Link probability between blocksWhat do the values of a square or rectangular result matrix look like at a glance?
View data
With blockBlockLink probability
Block 1Block 10.0121
Block 2Block 10.3154
Block 1Block 20.3154
Block 2Block 20.8444
Choosing the number of blocksHow many clusters does the data support?

Higher is better; BIC chose 2 blocks.

View data
BestCriterionBlocksCriterion
falseICL1−489.40
trueICL2−348.54
falseICL3−376.59
falseICL4−380.27
falseBIC1−489.40
trueBIC2−348.54
falseBIC3−359.65
falseBIC4−376.32
Adjacency matrix by blockWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by block: each tile of the matrix is one pair of blocks.

View data
ColumnBlockNodeOrderRowEdge
12c013001
22c024301
32c032201
42c042301
52c053101
62c061201
72c072501
82c083201
92c094001
102c104501
121p014601
141p024701
151p034801
161p041701
171p051801
191p062401
231p082601
251p093301
301p103501
311p114401
321p121001
331p131101
341p141401
351p151601
361p161901
391p172101
471p184101
21p191511
31p202011
41p212711
51p223411
61p233811
81p243911
91p254211
111p261311
181p272811
191p282911
211p293611
221p303711
251p31011
321p32111
401p33511
411p34211
421p35411
431p36911
451p37711
461p38311
481p39611
41p40821
5———21
6———21
7———21
8———21
11———21
12———21
13———21
14———21
17———21
23———21
24———21

First 60 of 170 rows.

Blocks in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromBlockNodeDegreeToxy
02c012710.06470.2206
02c02222−0.0703−0.0522
02c032130.0556−0.2756
02c041740.00110.1048
02c05215−0.2148−0.0705
02c062260.0092−0.1142
02c071670.18140.0672
02c081980.2416−0.1651
02c09149−0.0366−0.1490
02c102010−0.22930.1655
01p01312−0.37150.6393
01p02314−0.4997−0.1871
01p035150.1987−0.2454
01p041160.1736−1
01p053170.1100−0.4102
01p062190.48940.5501
01p08323−0.50820.3244
01p094250.5402−0.0508
01p104300.44640.0612
01p113310.09940.5200
01p12232−0.3263−0.4763
01p13333−0.4702−0.3604
01p146340.1060−0.0352
01p156350.21890.1485
01p16436−0.3539−0.0189
01p17539−0.16230.3314
01p184470.1637−0.5505
11p1922−0.19210.6509
11p2013−0.9067−0.2940
11p2114−0.87180.4965
11p2285−0.04430.0333
11p2366−0.29520.1515
11p24580.36380.2121
11p2549−0.45950.1276
11p262110.55050.2952
11p274180.3660−0.1414
11p281190.35360.8868
11p291210.8376−0.5543
11p302220.7614−0.1230
11p31225−0.15850.8464
11p32532−0.35140.4490
11p33340−0.1077−0.5990
11p342410.2435−0.6710
11p35742−0.00370.3144
11p364430.3518−0.3309
11p37545−0.1879−0.3302
11p38546−0.0777−0.3903
11p395480.24710.2456
21p4054−0.2757−0.2468
2———5——
2———6——
2———7——
2———8——
2———11——
2———12——
2———13——
2———14——
2———17——
2———23——
2———24——

First 60 of 170 rows.

Blocks

BlockNodesModel shareLink probability withinMean certaintyBest-connected nodes
13979.6%0.01211.0000p22, p35, p14
21020.4%0.84441.0000c01, c02, c06

Link probability between blocks

BlockBlock 1Block 2
Block 10.01210.3154
Block 20.31540.8444

Number of blocks

BlocksICLBICLower bound
1−489.40−489.40−485.87
2−348.54−348.54−335.99
3−376.59−359.65−334.55
4−380.27−376.32−335.13
The exact R script · R R version 4.5.1 (2025-06-13)
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec be4cf769b2dd9671
# Dataset: grf2_coreper_edges (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_ml_sbm_*(): twin of codesplash.ml.sbm

MODEL <- "bernoulli"
BLOCKS <- NULL
MAX_BLOCKS <- 4
CRITERION <- "bic"
STARTS <- 3L
SEED <- 42
MODEL_LABELS <- c(bernoulli = "stochastic blockmodel", poisson_dc = "degree-corrected blockmodel")
CRITERION_LABELS <- c(icl = "ICL", bic = "BIC")

# %% The network the host built (canonical node order, merged edges; cs_graph_read)
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.sbm/coreper_bic/out-r")
G <- cs_graph_read(out)
warnings <- as.list(G$warnings)
N <- G$n
pairs <- cs_graph_undirected_pairs(G) # direction set aside; repeated edges add up
a <- pairs$a; b <- pairs$b; w <- pairs$w
if (N > 2000 || length(a) > 200000) cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(a), max_nodes = 2000, max_edges = 200000)
if (N < 3 || length(a) == 0) cs_error("CS_E_UNDEFINED", what = "A stochastic blockmodel", reason = "it needs at least 3 nodes and one edge between two different nodes")
if (any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = if (!is.null(G$meta$weight)) G$meta$weight else "Edge count", requirement = "zero or more", count = sum(w < 0))
if (isTRUE(G$directed)) warnings <- c(warnings, "The blockmodel treats every edge as two-way, so the directions were set aside.")
A <- matrix(0, N, N)
if (MODEL == "bernoulli") {
  A[cbind(a + 1L, b + 1L)] <- 1
  if (isTRUE(G$weighted)) warnings <- c(warnings, "The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
} else {
  A[cbind(a + 1L, b + 1L)] <- w # link counts (1 per edge row without a weight column)
}
A[cbind(b + 1L, a + 1L)] <- A[cbind(a + 1L, b + 1L)]
values <- list(n_nodes = N, n_edges = length(a), density = length(a) / (N * (N - 1) / 2),
               model_label = MODEL_LABELS[[MODEL]], criterion_label = if (is.null(BLOCKS)) CRITERION_LABELS[[CRITERION]] else "you")

# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng <- cs_rng(SEED)
if (is.null(BLOCKS)) {
  q_max <- max(1, min(MAX_BLOCKS, N - 1))
  sel <- cs_ml_sbm_select(A, q_max, MODEL, rng, STARTS, CRITERION)
  Q <- sel$best
  fits <- sel$fits
  best <- fits[[Q]]
} else {
  Q <- as.integer(BLOCKS)
  if (Q > N - 1) cs_error("CS_E_INVALID_OPTION", option = "Blocks", allowed = sprintf("at most %d for %d nodes", N - 1, N), value = Q)
  best <- cs_ml_sbm_fit(A, Q, MODEL, rng, STARTS)
  fits <- NULL
}
cn <- cs_ml_sbm_canonical(best$tau, best$alpha, best$rate)
lab <- cn$labels; tau <- cn$tau; alpha <- cn$alpha; rate <- cn$rate
block <- lab + 1L # 1..Q by size, ties by first node
values$blocks <- Q
values$icl <- best$icl; values$bic <- best$bic; values$loglik <- best$loglik
values$elbo <- best$J
values$converged <- isTRUE(best$converged)
if (!isTRUE(best$converged)) warnings <- c(warnings, "Variational EM stopped at its iteration limit before the lower bound settled.")
certainty <- apply(tau, 1, max)
values$certainty <- mean(certainty)
sizes <- tabulate(block, nbins = Q)
edges <- matrix(0, Q, Q)
for (e in seq_along(a)) {
  p <- min(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L; q <- max(lab[a[e] + 1L], lab[b[e] + 1L]) + 1L
  edges[p, q] <- edges[p, q] + if (MODEL == "bernoulli") 1 else w[e]
}
for (q in seq_len(Q)) {
  values[[sprintf("size[%d]", q)]] <- sizes[q]
  values[[sprintf("share[%d]", q)]] <- alpha[q]
  for (l in q:Q) {
    values[[sprintf("rate[%d,%d]", q, l)]] <- rate[q, l]
    values[[sprintf("edges[%d,%d]", q, l)]] <- edges[q, l]
  }
}
if (!is.null(fits)) {
  for (i in seq_along(fits)) {
    values[[sprintf("icl[%d]", i)]] <- fits[[i]]$icl
    values[[sprintf("bic[%d]", i)]] <- fits[[i]]$bic
  }
}
if (!is.null(G$label)) {
  truth <- as.character(G$nodes[[G$label]])
  ok <- !is.na(truth)
  values$n_labeled <- sum(ok)
  if (sum(ok) >= 2) {
    values$ari <- cs_ml_ari(truth[ok], block[ok])
    values$ami <- cs_ml_ami(truth[ok], block[ok])
    values$nmi <- cs_ml_nmi(truth[ok], block[ok])
  }
}

# %% Tables
rate_label <- if (MODEL == "bernoulli") "Link probability" else "Rate per degree pair (λ)"
deg <- rowSums(A)
brows <- list()
for (q in seq_len(Q)) {
  members <- which(block == q)
  top <- members[order(-deg[members], members)][seq_len(min(3L, length(members)))]
  brows[[q]] <- list(block = q, size = sizes[q], share = alpha[q], within = rate[q, q],
                     certainty = if (length(members)) mean(certainty[members]) else NULL,
                     examples = paste(G$node_id[top], collapse = ", "))
}
tables <- list(list(
  key = "blocks", title = "Blocks",
  columns = list(list(key = "block", label = "Block", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
                 list(key = "share", label = "Model share", type = "percent"), list(key = "within", label = sprintf("%s within", rate_label), type = "number"),
                 list(key = "certainty", label = "Mean certainty", type = "number"), list(key = "examples", label = "Best-connected nodes")),
  rows = brows
))
mrows <- lapply(seq_len(Q), function(q) {
  row <- list(block = sprintf("Block %d", q))
  for (l in seq_len(Q)) row[[sprintf("b%d", l)]] <- rate[q, l]
  row
})
tables[[2]] <- list(
  key = "block_matrix", title = sprintf("%s between blocks", rate_label),
  columns = c(list(list(key = "block", label = "Block")), lapply(seq_len(Q), function(l) list(key = sprintf("b%d", l), label = sprintf("Block %d", l), type = "number"))),
  rows = mrows
)
if (!is.null(fits)) {
  tables[[3]] <- list(
    key = "selection", title = "Number of blocks",
    columns = list(list(key = "blocks", label = "Blocks", type = "integer"), list(key = "icl", label = "ICL", type = "number"),
                   list(key = "bic", label = "BIC", type = "number"), list(key = "elbo", label = "Lower bound", type = "number")),
    rows = lapply(seq_along(fits), function(i) list(blocks = i, icl = fits[[i]]$icl, bic = fits[[i]]$bic, elbo = fits[[i]]$J))
  )
}

# %% Node table and charts
artifacts <- list(cs_graph_write_nodes(out, G, data.frame(block = as.integer(block), certainty = certainty, degree = deg)))
names_ <- sprintf("Block %d", seq_len(Q))
level_names <- as.character(seq_len(Q))
charts <- list()
charts[[1]] <- cs_chart("block_matrix", "matrix-heatmap", sprintf("%s between blocks", rate_label), list(
  row = cs_col("Block", rep(names_, each = Q), "categorical", names_),
  col = cs_col("With block", rep(names_, times = Q), "categorical", names_),
  value = cs_col(rate_label, as.vector(t(rate)), "numeric")
), controls = list(scale = "sequential"))
if (!is.null(fits) && length(fits) > 1) {
  qs <- seq_along(fits)
  icl <- vapply(fits, function(f) f$icl, numeric(1))
  bic <- vapply(fits, function(f) f$bic, numeric(1))
  charts[[length(charts) + 1L]] <- cs_chart("selection", "elbow-plot", "Choosing the number of blocks", list(
    k = cs_col("Blocks", c(qs, qs), "numeric"),
    score = cs_col("Criterion", c(icl, bic), "numeric"),
    criterion = cs_col("Criterion", c(rep("ICL", length(qs)), rep("BIC", length(qs))), "categorical", c("ICL", "BIC")),
    chosen = cs_col("Best", c(qs == which.max(icl), qs == which.max(bic)), "boolean")
  ), note = sprintf("Higher is better; %s chose %d block%s.", CRITERION_LABELS[[CRITERION]], Q, if (Q != 1) "s" else ""))
}
if (N <= 300) {
  morder <- order(block, -deg, seq_len(N)) - 1L
  charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by block", list(
    row = cs_col("Row", G$si, "numeric"),
    col = cs_col("Column", G$sj, "numeric"),
    value = cs_col(if (isTRUE(G$weighted)) "Weight" else "Edge", G$sw, "numeric"),
    node = cs_col("Node", G$node_id, "categorical"),
    group = cs_col("Block", as.character(block), "categorical", level_names),
    order = cs_col("Order", morder, "numeric")
  ), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by block: each tile of the matrix is one pair of blocks.")
}
if (N <= 2000) {
  xy <- cs_graph_layout_fr(G, SEED)
  m <- length(G$si)
  show <- min(m, 20000)
  keep <- seq_len(show)
  charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Blocks in the network", list(
    x = cs_col("x", xy$x, "numeric"),
    y = cs_col("y", xy$y, "numeric"),
    node = cs_col("Node", G$node_id, "categorical"),
    size = cs_col("Degree", deg, "numeric"),
    group = cs_col("Block", as.character(block), "categorical", level_names),
    from = cs_col("From", G$si[keep], "numeric"),
    to = cs_col("To", G$sj[keep], "numeric"),
    weight = if (isTRUE(G$weighted)) cs_col("Weight", G$sw[keep], "numeric") else NULL
  ), controls = list(directed = isTRUE(G$directed)), note = if (show == m) NULL else sprintf("%d of %d edges drawn.", show, m))
}

# %% Result
how <- if (is.null(BLOCKS)) sprintf("chosen by %s", CRITERION_LABELS[[CRITERION]]) else "as set"
summary <- sprintf("The %s puts %s nodes in %d block%s (%s); the average node sits in its block with probability %.3f.",
                   MODEL_LABELS[[MODEL]], format(N, big.mark = ","), Q, if (Q != 1) "s" else "", how, values$certainty)
cs_publish(list(
  title = "Stochastic blockmodel",
  engine = cs_engine_info("nanoparquet"),
  n = N,
  summary = summary,
  statistics = list(list(key = "blocks", label = "Blocks", value = Q, format = "integer"),
                    list(key = "icl", label = "ICL", value = values$icl),
                    list(key = "certainty", label = "Mean certainty", value = values$certainty)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = artifacts
))
Python

The stochastic blockmodel puts 49 nodes in 2 blocks (chosen by BIC); the average node sits in its block with probability 1.000.

Blocks
2
ICL
−348.54
Mean certainty
1.0000

To keep this page light, the plots are shown once, under the R tab.

Blocks

BlockNodesModel shareLink probability withinMean certaintyBest-connected nodes
13979.6%0.01211.0000p22, p35, p14
21020.4%0.84441.0000c01, c02, c06

Link probability between blocks

BlockBlock 1Block 2
Block 10.01210.3154
Block 20.31540.8444

Number of blocks

BlocksICLBICLower bound
1−489.40−489.40−485.87
2−348.54−348.54−335.99
3−376.59−359.65−334.55
4−380.27−376.32−335.13
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Stochastic blockmodel
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.sbm 1.0.0 · spec be4cf769b2dd9671
# Dataset: grf2_coreper_edges (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import graph as cg
from codesplash import ml as csml
from codesplash.graph import layout as gl
from codesplash.ml import cluster as csc
from codesplash.ml import sbm  # twin of codesplashr R/ml_sbm.R
from codesplash.stats.rng import Rng

MODEL = "bernoulli"
BLOCKS = None
MAX_BLOCKS = 4
CRITERION = "bic"
STARTS = 3
SEED = 42
MODEL_LABELS = {"bernoulli": "stochastic blockmodel", "poisson_dc": "degree-corrected blockmodel"}
CRITERION_LABELS = {"icl": "ICL", "bic": "BIC"}

# %% The network the host built (canonical node order, merged edges; codesplash.graph)
out = csml.out_dir("target/academy-parity/run-8142/discover.sbm/coreper_bic/out-python")
G = cg.read(out)
warnings = list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)  # direction set aside; repeated edges add up
if N > 2000 or len(a) > 200000:
    cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=2000, max_edges=200000)
if N < 3 or len(a) == 0:
    cs.cs_error("CS_E_UNDEFINED", what="A stochastic blockmodel", reason="it needs at least 3 nodes and one edge between two different nodes")
if np.any(w < 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=G.meta.get("weight") or "Edge count", requirement="zero or more", count=int(np.sum(w < 0)))
if G.directed:
    warnings.append("The blockmodel treats every edge as two-way, so the directions were set aside.")
A = np.zeros((N, N))
if MODEL == "bernoulli":
    A[a, b] = 1.0
    if G.weighted:
        warnings.append("The plain blockmodel reads whether two nodes are linked, so edge weights were set aside.")
else:
    A[a, b] = w  # link counts (1 per edge row without a weight column)
A[b, a] = A[a, b]
values = {"n_nodes": N, "n_edges": int(len(a)), "density": float(len(a) / (N * (N - 1) / 2.0)),
          "model_label": MODEL_LABELS[MODEL], "criterion_label": CRITERION_LABELS[CRITERION] if BLOCKS is None else "you"}

# %% Fit: variational EM from k-means++ / Lloyd starts on the rows of A (shared stream)
rng = Rng(SEED)
if BLOCKS is None:
    q_max = max(1, min(MAX_BLOCKS, N - 1))
    sel = sbm.select(A, q_max, MODEL, rng, STARTS, CRITERION)
    Q = sel["best"]
    fits = sel["fits"]
    best = fits[Q - 1]
else:
    Q = int(BLOCKS)
    if Q > N - 1:
        cs.cs_error("CS_E_INVALID_OPTION", option="Blocks", allowed=f"at most {N - 1} for {N} nodes", value=Q)
    best = sbm.fit(A, Q, MODEL, rng, STARTS)
    fits = None
lab, tau, alpha, rate = sbm.canonical(best["tau"], best["alpha"], best["rate"])
block = lab + 1  # 1…Q by size, ties by first node
values["blocks"] = Q
for key in ("icl", "bic", "loglik"):
    values[key] = best[key]
values["elbo"] = best["J"]
values["converged"] = bool(best["converged"])
if not best["converged"]:
    warnings.append("Variational EM stopped at its iteration limit before the lower bound settled.")
certainty = tau.max(axis=1)
values["certainty"] = float(np.mean(certainty))
sizes = np.bincount(lab, minlength=Q)
edges = np.zeros((Q, Q))
for i, j, x in zip(a.tolist(), b.tolist(), w.tolist()):
    p, q = min(lab[i], lab[j]), max(lab[i], lab[j])
    edges[p, q] += 1.0 if MODEL == "bernoulli" else x
for q in range(Q):
    values[f"size[{q + 1}]"] = int(sizes[q])
    values[f"share[{q + 1}]"] = float(alpha[q])
    for l in range(q, Q):
        values[f"rate[{q + 1},{l + 1}]"] = float(rate[q, l])
        values[f"edges[{q + 1},{l + 1}]"] = float(edges[q, l])
if fits is not None:
    for i, f in enumerate(fits, start=1):
        values[f"icl[{i}]"] = f["icl"]
        values[f"bic[{i}]"] = f["bic"]
if G.label:
    truth = np.array([None if pd.isna(v) else str(v) for v in G.nodes[G.label].tolist()], dtype=object)  # None, NaN, pd.NA
    ok = np.array([v is not None for v in truth])
    values["n_labeled"] = int(ok.sum())
    if ok.sum() >= 2:
        tt = truth[ok].astype(str)
        values["ari"] = csc.ari(tt, block[ok])
        values["ami"] = csc.ami(tt, block[ok])
        values["nmi"] = csc.nmi(tt, block[ok])

# %% Tables
rate_label = "Link probability" if MODEL == "bernoulli" else "Rate per degree pair (λ)"
deg = A.sum(axis=1)
brows = []
for q in range(Q):
    members = np.flatnonzero(lab == q)
    top = sorted(members.tolist(), key=lambda v: (-deg[v], v))[:3]
    brows.append({"block": q + 1, "size": int(sizes[q]), "share": float(alpha[q]), "within": float(rate[q, q]),
                  "certainty": float(np.mean(certainty[members])) if len(members) else None,
                  "examples": ", ".join(G.node_id[v] for v in top)})
tables = [{
    "key": "blocks", "title": "Blocks",
    "columns": [{"key": "block", "label": "Block", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
                {"key": "share", "label": "Model share", "type": "percent"}, {"key": "within", "label": f"{rate_label} within", "type": "number"},
                {"key": "certainty", "label": "Mean certainty", "type": "number"}, {"key": "examples", "label": "Best-connected nodes"}],
    "rows": brows,
}]
mrows = []
for q in range(Q):
    row = {"block": f"Block {q + 1}"}
    for l in range(Q):
        row[f"b{l + 1}"] = float(rate[q, l])
    mrows.append(row)
tables.append({
    "key": "block_matrix", "title": f"{rate_label} between blocks",
    "columns": [{"key": "block", "label": "Block"}] + [{"key": f"b{l + 1}", "label": f"Block {l + 1}", "type": "number"} for l in range(Q)],
    "rows": mrows,
})
if fits is not None:
    tables.append({
        "key": "selection", "title": "Number of blocks",
        "columns": [{"key": "blocks", "label": "Blocks", "type": "integer"}, {"key": "icl", "label": "ICL", "type": "number"},
                    {"key": "bic", "label": "BIC", "type": "number"}, {"key": "elbo", "label": "Lower bound", "type": "number"}],
        "rows": [{"blocks": i, "icl": f["icl"], "bic": f["bic"], "elbo": f["J"]} for i, f in enumerate(fits, start=1)],
    })

# %% Node table and charts
artifacts = [cg.write_nodes(out, G, {"block": block.astype(np.int64), "certainty": certainty, "degree": deg})]
names = [f"Block {q + 1}" for q in range(Q)]
level_names = [str(q + 1) for q in range(Q)]
charts = []
cells_r, cells_c, cells_v = [], [], []
for q in range(Q):
    for l in range(Q):
        cells_r.append(names[q])
        cells_c.append(names[l])
        cells_v.append(float(rate[q, l]))
charts.append(cs.chart("block_matrix", "matrix-heatmap", f"{rate_label} between blocks", {
    "row": cs.col("Block", cells_r, "categorical", names),
    "col": cs.col("With block", cells_c, "categorical", names),
    "value": cs.col(rate_label, cells_v, "numeric"),
}, controls={"scale": "sequential"}))
if fits is not None and len(fits) > 1:
    qs = list(range(1, len(fits) + 1))
    icl = [f["icl"] for f in fits]
    bic = [f["bic"] for f in fits]
    charts.append(cs.chart("selection", "elbow-plot", "Choosing the number of blocks", {
        "k": cs.col("Blocks", qs + qs, "numeric"),
        "score": cs.col("Criterion", icl + bic, "numeric"),
        "criterion": cs.col("Criterion", ["ICL"] * len(qs) + ["BIC"] * len(qs), "categorical", ["ICL", "BIC"]),
        "chosen": cs.col("Best", [q == 1 + int(np.argmax(icl)) for q in qs] + [q == 1 + int(np.argmax(bic)) for q in qs], "boolean"),
    }, note=f"Higher is better; {CRITERION_LABELS[CRITERION]} chose {Q} block{'s' if Q != 1 else ''}."))
if N <= 300:
    morder = sorted(range(N), key=lambda v: (int(block[v]), -deg[v], v))
    charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by block", {
        "row": cs.col("Row", G.si, "numeric"),
        "col": cs.col("Column", G.sj, "numeric"),
        "value": cs.col("Weight" if G.weighted else "Edge", G.sw, "numeric"),
        "node": cs.col("Node", G.node_id, "categorical"),
        "group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
        "order": cs.col("Order", morder, "numeric"),
    }, controls={"directed": G.directed}, note="Nodes sorted by block: each tile of the matrix is one pair of blocks."))
if N <= 2000:
    xy = gl.fruchterman_reingold(G, SEED)
    m = len(G.si)
    show = min(m, 20000)
    charts.append(cs.chart("map", "network-graph", "Blocks in the network", {
        "x": cs.col("x", xy[0], "numeric"),
        "y": cs.col("y", xy[1], "numeric"),
        "node": cs.col("Node", G.node_id, "categorical"),
        "size": cs.col("Degree", deg, "numeric"),
        "group": cs.col("Block", [str(q) for q in block], "categorical", level_names),
        "from": cs.col("From", G.si[:show], "numeric"),
        "to": cs.col("To", G.sj[:show], "numeric"),
        "weight": cs.col("Weight", G.sw[:show], "numeric") if G.weighted else None,
    }, controls={"directed": G.directed}, note=None if show == m else f"{show} of {m} edges drawn."))

# %% Result
how = f"chosen by {CRITERION_LABELS[CRITERION]}" if BLOCKS is None else "as set"
summary = (f"The {MODEL_LABELS[MODEL]} puts {N:,} nodes in {Q} block{'s' if Q != 1 else ''} ({how}); "
           f"the average node sits in its block with probability {values['certainty']:.3f}.")
cs.publish({
    "title": "Stochastic blockmodel",
    "engine": cs.engine_info("numpy", "pandas", "scikit-learn"),
    "n": N,
    "summary": summary,
    "statistics": [
        {"key": "blocks", "label": "Blocks", "value": Q, "format": "integer"},
        {"key": "icl", "label": "ICL", "value": values["icl"]},
        {"key": "certainty", "label": "Mean certainty", "value": values["certainty"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": artifacts,
})

Here BIC picks 2 blocks: a core of 10 nodes linked to each other with probability 0.84, and a periphery that links mostly to the core.

07

Mixed memberships

Read

People play several roles: colleague in one interaction, friend in another. The mixed-membership blockmodelMixed-membership stochastic blockmodelA network model where each node has a blend of roles and picks one per relationship, so a link's chance is πᵢᵀBπⱼ. gives each node a membership vector πi\pi_i (a Dirichlet draw). For each ordered pair, the sender picks a role from πi\pi_i and the receiver from πj\pi_j; a link appears with the block matrix's probability. Averaged over roles,

P(Aij=1)=πi⊤B πj.P(A_{ij} = 1) = \pi_i^\top B\, \pi_j .

In the reference's example, two nodes that are each 90% role 1 link with probability 0.682. Sparse graphs, very uneven degrees and missing edges distort memberships, and role labels can switch.

08

Readiness

Read
  • HMM (REP049) runs in CodeSplash: Hidden Markov model, for Gaussian, Poisson or categorical sequences, one or many.
  • MMSB (REP050): CodeSplash now loads networks as edge lists and fits one-block-per-node blockmodels (Discover → Stochastic blockmodel, Experimental). Mixed memberships aren't fitted; the readiness badge shows the entry's current label.
Reference · REP050 · Runs as a notebookMixed-membership stochastic blockmodel (MMSB)Give each network node a mixture of latent roles, allowing its role to differ across interactions rather than assigning it one fixed community.
09

Check: HMMs and blockmodels

Checkpoint

Check yourself

A state stays put with probability Akk=0.8A_{kk} = 0.8 each step. What is its expected stay, in steps?

Show the answer

Answer: 5

1/(1−0.8)=51/(1 - 0.8) = 5.

Check yourself

Why does the forward algorithm make HMM likelihoods practical?

Show the answer

Answer: a

There are KTK^T paths, but the recursion αt=(αt−1A)⊙b(xt)\alpha_t = (\alpha_{t-1}A)\odot b(x_t) needs only O(TK2)O(TK^2) work. Viterbi is the max version that finds the single best path.

Check yourself

Two HMM fits on the same data have identical likelihoods, but state 1 in the first has the emission mean of state 2 in the second. What happened?

Show the answer

Answer: a

Swapping state labels leaves the likelihood unchanged. Match states by their emissions before comparing.

Check yourself

Machine faults usually last about 3 hours, rarely much less. Why might a plain HMM describe them poorly?

Show the answer

Answer: a

A geometric distribution peaks at 1 step. Durations with a typical length need a hidden semi-Markov model.

Check yourself

Two roles with block matrix B=(0.80.20.20.8)B = \begin{pmatrix}0.8 & 0.2\\ 0.2 & 0.8\end{pmatrix}. Node ii has πi=(1,0)\pi_i = (1, 0) and node jj has πj=(0.5,0.5)\pi_j = (0.5, 0.5). What is P(Aij=1)=πi⊤BπjP(A_{ij} = 1) = \pi_i^\top B \pi_j?

Show the answer

Answer: 0.5

πi⊤B=(0.8,0.2)\pi_i^\top B = (0.8, 0.2), and (0.8,0.2)⋅(0.5,0.5)=0.4+0.1=0.5(0.8, 0.2)\cdot(0.5, 0.5) = 0.4 + 0.1 = 0.5.

Check yourself

What can a mixed-membership blockmodel express that a stochastic blockmodel can't?

Show the answer

Answer: a

A stochastic blockmodel fixes one block per node. Mixed membership lets the role vary from one pair to the next.

10

Recap

Recap
  • An HMM represents a sequence as a path of hidden states; the forward algorithm sums over paths efficiently.
  • Watch geometric stays, label switching and local optima.
  • Blockmodels represent networks by roles; MMSB lets each node mix roles, which CodeSplash explains but doesn't fit.

Concepts in this lesson