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.
What runs in CodeSplash
- REP049Hidden Markov model (HMM) Runs in CodeSplash
- REP050Mixed-membership stochastic blockmodel (MMSB) Runs as a notebook
- Hidden Markov model (regimes in a sequence) Verified in Python and R
- Stochastic blockmodel Experimental
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
A sequence driven by unseen states
ReadA 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 hidden states. Each step, the state may switch according to a transition matrix , and the observation is drawn from that state's emission distribution :
The representation of a sequence is its path of states: a few regimes instead of hundreds of raw values.
The forward algorithm
ReadThe likelihood sums over every possible state path, but the forward algorithm does it in : carry a vector of "probability so far, ending in each state", and update
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 and from forward–backward probabilities.
Old Faithful's waiting times
ReadA 2-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 55.44 (stay 1.08 steps); State 2 mean 80.53 (stay 1.72 steps). Log-likelihood -997.22, BIC 2033.7.
- Log-likelihood
- −997.22
- BIC
- 2033.68
- AIC
- 2008.44
Assumptions
- First-order Markov states — Assumed, not checked from the data: the next state depends only on the current one, the transition probabilities stay the same over time, and each observation depends only on its state.
- Same optimum from different starts — 3 of 3 starts reached the best log-likelihood (-997.2188).
States
| State | Mean | SD | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|---|
| State 1 | 55.436 | 6.609 | 6.777e-82 | 38.5% | 38.2% | 1.075 | 1.072 |
| State 2 | 80.527 | 5.478 | 1 | 61.5% | 61.8% | 1.716 | 1.714 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.0698 | 0.9302 |
| State 2 | 0.5828 | 0.4172 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 2 | 1 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 2 | 0.9997 |
| 4 | 62 | State 1 | 0.9979 |
| 5 | 85 | State 2 | 1.0000 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 2 | 1.0000 |
| 8 | 85 | State 2 | 1.0000 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 2 | 1.0000 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 2 | 1.0000 |
| 13 | 78 | State 2 | 0.9995 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 2 | 1.0000 |
| 16 | 52 | State 1 | 1.0000 |
| 17 | 62 | State 1 | 0.9626 |
| 18 | 84 | State 2 | 1.0000 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 2 | 1.0000 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.9999 |
| 24 | 69 | State 1 | 0.7240 |
| 25 | 74 | State 2 | 0.9706 |
| 26 | 83 | State 2 | 1.0000 |
| 27 | 55 | State 1 | 1.0000 |
| 28 | 76 | State 2 | 0.9985 |
| 29 | 78 | State 2 | 0.9917 |
| 30 | 79 | State 2 | 0.9961 |
| 31 | 73 | State 2 | 0.8381 |
| 32 | 77 | State 2 | 0.9988 |
| 33 | 66 | State 1 | 0.9598 |
| 34 | 80 | State 2 | 0.9998 |
| 35 | 74 | State 2 | 0.9946 |
| 36 | 52 | State 1 | 1.0000 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 2 | 1.0000 |
| 39 | 59 | State 1 | 0.9998 |
| 40 | 90 | State 2 | 1.0000 |
First 40 of 272 rows.
- EM (Baum–Welch) from 3 start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed 42; the best log-likelihood is kept. States are numbered by increasing mean, so labels don't switch between runs.
- Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.
- The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.
The exact R script · R R version 4.5.1 (2025-06-13)
# Hidden Markov model (regimes in a sequence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.hmm 1.0.0 · spec f4a30f1592589bdf
# Dataset: h_faithful (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/h_faithful.parquet", col_select = c("waiting")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("waiting")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("waiting")) # infinite values stop the run (registry/errors.yaml)
# %% Sequences
# A K-state hidden Markov model (Baum-Welch EM; Rabiner 1989): one observation per time step, several
# sequences sharing the parameters, states in a canonical order (increasing mean or rate).
VALUE <- "waiting"
SEQUENCE <- NULL
TIME <- NULL
TEMPORAL <- FALSE
VALUE_CATEGORICAL <- FALSE
EMISSION <- "auto"
K <- as.integer(2)
SHARED_VAR <- FALSE
STARTS <- as.integer(3)
SCAN <- FALSE
SCAN_MAX <- as.integer(4)
MAX_ITER <- as.integer(300)
SEED <- 42
d <- df
if (!is.null(SEQUENCE) && !is.null(TIME)) {
d <- d[order(as.integer(d[[SEQUENCE]]), d[[TIME]], method = "radix"), , drop = FALSE]
} else if (!is.null(SEQUENCE)) {
d <- d[order(as.integer(d[[SEQUENCE]]), method = "radix"), , drop = FALSE]
} else if (!is.null(TIME)) {
d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
}
rownames(d) <- NULL
n <- nrow(d)
cs_check_rows(n, max(10, 5 * K), "A hidden Markov model")
if (VALUE_CATEGORICAL) {
if (EMISSION %in% c("gaussian", "poisson"))
cs_error("CS_E_INVALID_OPTION", option = "Emission distribution", allowed = "categorical for a categorical column", value = EMISSION)
family <- "categorical"
levs <- as.character(levels(d[[VALUE]]))
cs_check_groups(as.character(d[[VALUE]]), VALUE, minimum = 2)
x_all <- as.integer(d[[VALUE]])
} else {
family <- if (EMISSION == "auto") "gaussian" else EMISSION
raw <- as.numeric(d[[VALUE]])
cs_check_not_constant(raw, VALUE)
if (family == "categorical") {
uniq <- sort(unique(raw))
if (length(uniq) > 50) cs_error("CS_E_TOO_MANY_LEVELS", column = VALUE, k = length(uniq), max = 50)
levs <- sprintf("%.6g", uniq)
x_all <- match(raw, uniq)
} else {
levs <- character(0)
x_all <- raw
if (family == "poisson") {
bad <- sum(raw < 0 | raw != floor(raw))
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = VALUE, requirement = "whole numbers of 0 or more (counts)", count = bad)
}
}
}
n_levels <- length(levs)
seq_ids <- if (!is.null(SEQUENCE)) as.character(d[[SEQUENCE]]) else rep("1", n)
seq_names <- if (!is.null(SEQUENCE)) as.character(levels(d[[SEQUENCE]])) else "1"
rl <- rle(seq_ids)
ends <- cumsum(rl$lengths)
starts_ <- ends - rl$lengths + 1
seqs <- lapply(seq_along(ends), function(i) x_all[starts_[i]:ends[i]])
step <- unlist(lapply(rl$lengths, seq_len), use.names = FALSE)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else list()
if (!is.null(TIME)) {
keycols <- c(SEQUENCE, TIME)
dups <- sum(duplicated(d[keycols]))
if (dups > 0) warnings <- c(warnings, sprintf("%d rows repeat a time within their sequence; they are kept in row order, one step each.", dups))
}
# %% Fit
fit <- cs_hmm_fit(seqs, family, K, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
par <- fit$par
pi0 <- fit$pi
A <- fit$A
path <- cs_hmm_viterbi(seqs, family, par, pi0, A)
gamma <- fit$gamma
statd <- cs_hmm_stationary(A)
N <- length(x_all)
ll <- fit$loglik
p_free <- fit$n_params
values <- list(n_obs = N, n_sequences = length(seqs), n_states = K, family = family, n_levels = n_levels,
loglik = ll, n_params = p_free, aic = -2 * ll + 2 * p_free, bic = -2 * ll + p_free * log(N),
iterations = fit$iterations, converged = as.integer(fit$converged), starts = max(1L, STARTS),
starts_agree = fit$starts_agree, best_start = fit$start)
switches <- 0
runs <- lapply(seq_len(K), function(k) numeric(0))
for (i in seq_along(ends)) {
a <- starts_[i]
b <- ends[i]
r0 <- a
for (t in (a + 1):(b + 1)) {
if (t == b + 1 || path[t] != path[t - 1]) {
s <- path[t - 1]
runs[[s]] <- c(runs[[s]], t - r0)
if (t <= b) switches <- switches + 1
r0 <- t
}
}
}
values$switches <- switches
state_names <- sprintf("State %d", seq_len(K))
rows <- list()
for (k in seq_len(K)) {
share <- mean(path == k)
dur <- if (A[k, k] < 1) 1 / (1 - A[k, k]) else NaN
values[[sprintf("pi[%d]", k)]] <- pi0[k]
values[[sprintf("stationary[%d]", k)]] <- statd[k]
values[[sprintf("share[%d]", k)]] <- share
values[[sprintf("duration[%d]", k)]] <- dur
values[[sprintf("mean_run[%d]", k)]] <- if (length(runs[[k]])) mean(runs[[k]]) else NaN
row <- list(state = state_names[k], initial = pi0[k], stationary = statd[k], share = share, duration = dur,
mean_run = values[[sprintf("mean_run[%d]", k)]])
if (family == "gaussian") {
values[[sprintf("mean[%d]", k)]] <- par$mean[k]
values[[sprintf("sd[%d]", k)]] <- sqrt(par$var[k])
row$mean <- par$mean[k]
row$sd <- sqrt(par$var[k])
} else if (family == "poisson") {
values[[sprintf("rate[%d]", k)]] <- par$rate[k]
row$rate <- par$rate[k]
} else {
o <- order(-par$prob[k, ], method = "radix")[seq_len(min(3, n_levels))]
row$top <- paste(sprintf("%s (%.2f)", levs[o], par$prob[k, o]), collapse = ", ")
for (cc in seq_len(n_levels)) values[[sprintf("prob[%d:%s]", k, levs[cc])]] <- par$prob[k, cc]
}
for (j in seq_len(K)) values[[sprintf("transition[%d,%d]", k, j)]] <- A[k, j]
rows[[k]] <- row
}
# %% Choosing the number of states
scan_rows <- list()
if (SCAN) {
for (kk in seq_len(SCAN_MAX)) {
f_ <- if (kk == K) fit else cs_hmm_fit(seqs, family, kk, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
bic_ <- -2 * f_$loglik + f_$n_params * log(N)
aic_ <- -2 * f_$loglik + 2 * f_$n_params
scan_rows[[kk]] <- list(states = kk, loglik = f_$loglik, params = f_$n_params, aic = aic_, bic = bic_)
values[[sprintf("scan_loglik[%d]", kk)]] <- f_$loglik
values[[sprintf("scan_aic[%d]", kk)]] <- aic_
values[[sprintf("scan_bic[%d]", kk)]] <- bic_
}
bics <- vapply(scan_rows, function(r) r$bic, numeric(1))
best_k <- scan_rows[[which.min(bics)]]$states
values$best_k_bic <- best_k
for (i in seq_along(scan_rows)) scan_rows[[i]]$best <- if (scan_rows[[i]]$states == best_k) "lowest BIC" else ""
}
# %% Assumptions
nst <- max(1L, STARTS)
assumptions <- list(list(key = "markov", label = "First-order Markov states", status = "info",
detail = paste0("Assumed, not checked from the data: the next state depends only on the current one, the transition ",
"probabilities stay the same over time, and each observation depends only on its state.")))
if (nst == 1) {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "info",
detail = "One start only: EM can stop at a local optimum; use several starts to check.")
} else if (fit$starts_agree >= 2) {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "pass",
detail = sprintf("%d of %d starts reached the best log-likelihood (%.4f).", fit$starts_agree, nst, ll))
} else {
assumptions[[2]] <- list(key = "stable_fit", label = "Same optimum from different starts", status = "warn",
detail = sprintf("Only start %d of %d reached the best log-likelihood (%.4f); the others stopped lower. Add starts before trusting the states.",
fit$start, nst, ll))
}
# %% Charts
charts <- list()
first_n <- ends[1]
xs <- if (!is.null(TIME)) labels[seq_len(first_n)] else seq_len(first_n)
xkind <- if (TEMPORAL) "temporal" else "numeric"
xname <- if (is.null(TIME)) "step" else TIME
first_title <- if (!is.null(SEQUENCE) && length(seqs) > 1) sprintf(" (%s %s)", SEQUENCE, seq_names[1]) else ""
if (family != "categorical") {
charts[[length(charts) + 1]] <- cs_chart("states", "segment-means", sprintf("%s with the most probable states%s", VALUE, first_title), list(
x = cs_col(xname, xs, kind = xkind), y = cs_col(VALUE, x_all[seq_len(first_n)]),
segment = cs_col("state", state_names[path[seq_len(first_n)]], kind = "categorical")))
}
if (K > 1 && first_n <= 5000) {
charts[[length(charts) + 1]] <- cs_chart("posterior", "series-line", sprintf("Probability of each state over time%s", first_title), list(
x = cs_col(xname, rep(xs, each = K), kind = xkind),
y = cs_col("probability", as.vector(t(gamma[seq_len(first_n), , drop = FALSE]))),
group = cs_col("state", rep(state_names, times = first_n), kind = "categorical")))
}
charts[[length(charts) + 1]] <- cs_chart("transitions", "matrix-heatmap", "Transition probabilities (row = from, column = to)", list(
row = cs_col("from", rep(state_names, each = K), kind = "categorical"),
col = cs_col("to", rep(state_names, times = K), kind = "categorical"),
value = cs_col("probability", as.vector(t(A))),
label = cs_col("text", sprintf("%.2f", as.vector(t(A))), kind = "categorical")))
if (length(scan_rows)) {
charts[[length(charts) + 1]] <- cs_chart("scan", "series-line", "Information criteria by number of states (lower is better)", list(
x = cs_col("states", as.numeric(rep(vapply(scan_rows, function(r) r$states, numeric(1)), each = 2))),
y = cs_col("criterion", as.vector(rbind(vapply(scan_rows, function(r) r$aic, numeric(1)), vapply(scan_rows, function(r) r$bic, numeric(1))))),
group = cs_col("criterion name", rep(c("AIC", "BIC"), times = length(scan_rows)), kind = "categorical")))
}
# %% Tables
state_cols <- list(list(key = "state", label = "State", type = "string"))
if (family == "gaussian") {
state_cols <- c(state_cols, list(list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number")))
} else if (family == "poisson") {
state_cols <- c(state_cols, list(list(key = "rate", label = "Rate", type = "number")))
} else {
state_cols <- c(state_cols, list(list(key = "top", label = "Most likely values", type = "string")))
}
state_cols <- c(state_cols, list(list(key = "initial", label = "Initial probability", type = "number"),
list(key = "stationary", label = "Long-run share", type = "percent"),
list(key = "share", label = "Share of steps (most probable path)", type = "percent"),
list(key = "duration", label = "Expected stay (steps)", type = "number"),
list(key = "mean_run", label = "Mean run in path (steps)", type = "number")))
trans_cols <- c(list(list(key = "from", label = "From", type = "string")),
lapply(seq_len(K), function(j) list(key = sprintf("to%d", j), label = sprintf("To %s", state_names[j]), type = "number")))
trans_rows <- lapply(seq_len(K), function(i) c(list(from = state_names[i]), stats::setNames(as.list(A[i, ]), sprintf("to%d", seq_len(K)))))
tables <- list(list(key = "states", title = "States", columns = state_cols, rows = rows),
list(key = "transitions", title = "Transition probabilities", columns = trans_cols, rows = trans_rows))
if (family == "categorical") {
tables[[length(tables) + 1]] <- list(key = "emissions", title = "Emission probabilities",
columns = c(list(list(key = "state", label = "State", type = "string")),
lapply(seq_len(n_levels), function(cc) list(key = sprintf("c%d", cc), label = levs[cc], type = "number"))),
rows = lapply(seq_len(K), function(k) c(list(state = state_names[k]), stats::setNames(as.list(par$prob[k, ]), sprintf("c%d", seq_len(n_levels))))))
}
if (length(scan_rows)) {
tables[[length(tables) + 1]] <- list(key = "scan", title = "Choosing the number of states",
columns = list(list(key = "states", label = "States", type = "integer"), list(key = "loglik", label = "Log-likelihood", type = "number"),
list(key = "params", label = "Parameters", type = "integer"), list(key = "aic", label = "AIC", type = "number"),
list(key = "bic", label = "BIC", type = "number"), list(key = "best", label = "", type = "string")),
rows = scan_rows)
}
CAP <- 2000
shown <- min(N, CAP)
path_rows <- lapply(seq_len(shown), function(i) {
r <- list()
r$sequence <- seq_ids[i]
r$time <- if (!is.null(TIME)) as.character(labels[[i]]) else as.character(step[i])
r$value <- if (family == "categorical") levs[x_all[i]] else x_all[i]
r$state <- state_names[path[i]]
r$posterior <- gamma[i, path[i]]
r
})
path_cols <- c(if (!is.null(SEQUENCE)) list(list(key = "sequence", label = SEQUENCE, type = "string")) else list(),
list(list(key = "time", label = if (is.null(TIME)) "Step" else TIME, type = "string"),
list(key = "value", label = VALUE, type = if (family == "categorical") "string" else "number"),
list(key = "state", label = "State", type = "string"),
list(key = "posterior", label = "Probability of that state", type = "number")))
tables[[length(tables) + 1]] <- list(key = "path", title = paste0("Most probable state of each step", if (N > CAP) sprintf(" (first %d of %d)", CAP, N) else ""),
columns = path_cols, rows = path_rows)
# %% Result
fam_label <- c(gaussian = "Gaussian", poisson = "Poisson", categorical = "categorical")[[family]]
where <- if (length(seqs) > 1) sprintf(" over %d sequences", length(seqs)) else ""
desc <- if (family == "gaussian") {
paste(vapply(seq_len(K), function(k) sprintf("%s mean %s (stay %s steps)", state_names[k], formatC(par$mean[k], digits = 4, format = "g"),
formatC(values[[sprintf("duration[%d]", k)]], digits = 3, format = "g")), ""), collapse = "; ")
} else if (family == "poisson") {
paste(vapply(seq_len(K), function(k) sprintf("%s rate %s (stay %s steps)", state_names[k], formatC(par$rate[k], digits = 4, format = "g"),
formatC(values[[sprintf("duration[%d]", k)]], digits = 3, format = "g")), ""), collapse = "; ")
} else {
paste(vapply(seq_len(K), function(k) sprintf("%s mostly %s", state_names[k], levs[which.max(par$prob[k, ])]), ""), collapse = "; ")
}
summary <- sprintf("A %d-state hidden Markov model with %s emissions for %s (%d steps%s): %s. Log-likelihood %.2f, BIC %.1f.",
K, fam_label, VALUE, N, where, desc, ll, values$bic)
if (!fit$converged) warnings <- c(warnings, cs_warning("CS_W_NO_CONVERGENCE", what = "The EM fit of the hidden Markov model"))
notes <- c(paste0(sprintf("EM (Baum–Welch) from %d start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed %d; ", nst, SEED),
"the best log-likelihood is kept. States are numbered by increasing ",
if (family == "gaussian") "mean" else if (family == "poisson") "rate" else "probability of the most common value, reversed",
", so labels don't switch between runs."),
"Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.",
"The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.")
statistics <- list(list(key = "loglik", label = "Log-likelihood", value = ll), list(key = "bic", label = "BIC", value = values$bic),
list(key = "aic", label = "AIC", value = values$aic))
cs_publish(list(
method = "ts.hmm",
methodVersion = "1.0.0",
title = "Hidden Markov model",
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
A 2-state hidden Markov model with Gaussian emissions for waiting (272 steps): State 1 mean 55.44 (stay 1.08 steps); State 2 mean 80.53 (stay 1.72 steps). Log-likelihood -997.22, BIC 2033.7.
- Log-likelihood
- −997.22
- BIC
- 2033.68
- AIC
- 2008.44
Assumptions
- First-order Markov states — Assumed, not checked from the data: the next state depends only on the current one, the transition probabilities stay the same over time, and each observation depends only on its state.
- Same optimum from different starts — 3 of 3 starts reached the best log-likelihood (-997.2188).
States
| State | Mean | SD | Initial probability | Long-run share | Share of steps (most probable path) | Expected stay (steps) | Mean run in path (steps) |
|---|---|---|---|---|---|---|---|
| State 1 | 55.436 | 6.609 | 6.777e-82 | 38.5% | 38.2% | 1.075 | 1.072 |
| State 2 | 80.527 | 5.478 | 1.0000 | 61.5% | 61.8% | 1.716 | 1.714 |
Transition probabilities
| From | To State 1 | To State 2 |
|---|---|---|
| State 1 | 0.0698 | 0.9302 |
| State 2 | 0.5828 | 0.4172 |
Most probable state of each step
| Step | waiting | State | Probability of that state |
|---|---|---|---|
| 1 | 79 | State 2 | 1.000 |
| 2 | 54 | State 1 | 1.0000 |
| 3 | 74 | State 2 | 0.9997 |
| 4 | 62 | State 1 | 0.9979 |
| 5 | 85 | State 2 | 1.0000 |
| 6 | 55 | State 1 | 1.0000 |
| 7 | 88 | State 2 | 1.0000 |
| 8 | 85 | State 2 | 1.0000 |
| 9 | 51 | State 1 | 1.0000 |
| 10 | 85 | State 2 | 1.0000 |
| 11 | 54 | State 1 | 1.0000 |
| 12 | 84 | State 2 | 1.0000 |
| 13 | 78 | State 2 | 0.9995 |
| 14 | 47 | State 1 | 1.0000 |
| 15 | 83 | State 2 | 1.0000 |
| 16 | 52 | State 1 | 1.0000 |
| 17 | 62 | State 1 | 0.9626 |
| 18 | 84 | State 2 | 1.0000 |
| 19 | 52 | State 1 | 1.0000 |
| 20 | 79 | State 2 | 1.0000 |
| 21 | 51 | State 1 | 1.0000 |
| 22 | 47 | State 1 | 1.0000 |
| 23 | 78 | State 2 | 0.9999 |
| 24 | 69 | State 1 | 0.7240 |
| 25 | 74 | State 2 | 0.9706 |
| 26 | 83 | State 2 | 1.0000 |
| 27 | 55 | State 1 | 1.0000 |
| 28 | 76 | State 2 | 0.9985 |
| 29 | 78 | State 2 | 0.9917 |
| 30 | 79 | State 2 | 0.9961 |
| 31 | 73 | State 2 | 0.8381 |
| 32 | 77 | State 2 | 0.9988 |
| 33 | 66 | State 1 | 0.9598 |
| 34 | 80 | State 2 | 0.9998 |
| 35 | 74 | State 2 | 0.9946 |
| 36 | 52 | State 1 | 1.0000 |
| 37 | 48 | State 1 | 1.0000 |
| 38 | 80 | State 2 | 1.0000 |
| 39 | 59 | State 1 | 0.9998 |
| 40 | 90 | State 2 | 1.0000 |
First 40 of 272 rows.
- EM (Baum–Welch) from 3 start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed 42; the best log-likelihood is kept. States are numbered by increasing mean, so labels don't switch between runs.
- Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.
- The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hidden Markov model (regimes in a sequence)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.hmm 1.0.0 · spec f4a30f1592589bdf
# Dataset: h_faithful (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import hmm, ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/h_faithful.parquet", columns=["waiting"])
n_input = len(df)
df = df.dropna(subset=["waiting"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["waiting"]) # infinite values stop the run (registry/errors.yaml)
# %% Sequences
# A K-state hidden Markov model (Baum–Welch EM; Rabiner 1989): one observation per time step, several
# sequences sharing the parameters, states in a canonical order (increasing mean or rate).
VALUE = "waiting"
SEQUENCE = None
TIME = None
TEMPORAL = False
VALUE_CATEGORICAL = False
EMISSION = "auto"
K = int(2)
SHARED_VAR = False
STARTS = int(3)
SCAN = False
SCAN_MAX = int(4)
MAX_ITER = int(300)
SEED = 42
keys = ([SEQUENCE] if SEQUENCE else []) + ([TIME] if TIME else [])
d = df.sort_values(keys, kind="mergesort").reset_index(drop=True) if keys else df.reset_index(drop=True)
n = len(d)
cs.check_rows(n, max(10, 5 * K), "A hidden Markov model")
if VALUE_CATEGORICAL:
if EMISSION in ("gaussian", "poisson"):
cs.cs_error("CS_E_INVALID_OPTION", option="Emission distribution", allowed="categorical for a categorical column", value=EMISSION)
family = "categorical"
levels = [str(v) for v in d[VALUE].cat.categories]
check_groups(d[VALUE].astype(str), VALUE, minimum=2)
x_all = d[VALUE].cat.codes.to_numpy().astype(float)
else:
family = "gaussian" if EMISSION == "auto" else EMISSION
raw = d[VALUE].to_numpy(dtype=float)
check_not_constant(raw, VALUE)
if family == "categorical":
uniq = np.unique(raw)
if len(uniq) > 50:
cs.cs_error("CS_E_TOO_MANY_LEVELS", column=VALUE, k=len(uniq), max=50)
levels = ["%.6g" % v for v in uniq]
x_all = np.searchsorted(uniq, raw).astype(float)
else:
levels = []
x_all = raw
if family == "poisson":
bad = int(np.sum((raw < 0) | (raw != np.floor(raw))))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=VALUE, requirement="whole numbers of 0 or more (counts)", count=bad)
n_levels = len(levels)
seq_ids = [str(v) for v in d[SEQUENCE]] if SEQUENCE else ["1"] * n
seq_names = [str(v) for v in d[SEQUENCE].cat.categories] if SEQUENCE else ["1"]
bounds = []
start = 0
for i in range(1, n + 1):
if i == n or seq_ids[i] != seq_ids[i - 1]:
bounds.append((start, i))
start = i
seqs = [x_all[a:b] for a, b in bounds]
step = np.concatenate([np.arange(1, b - a + 1) for a, b in bounds])
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else []
if TIME:
dups = int(d.duplicated(subset=keys).sum())
if dups:
warnings.append(f"{dups} rows repeat a time within their sequence; they are kept in row order, one step each.")
# %% Fit
fit = hmm.fit(seqs, family, K, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
par, pi0, A = fit["par"], fit["pi"], fit["A"]
path = hmm.viterbi(seqs, family, par, pi0, A)
gamma = fit["gamma"]
statd = hmm.stationary(A)
N = len(x_all)
ll = fit["loglik"]
p_free = fit["n_params"]
values = {"n_obs": N, "n_sequences": len(seqs), "n_states": K, "family": family, "n_levels": n_levels,
"loglik": ll, "n_params": p_free, "aic": -2 * ll + 2 * p_free, "bic": -2 * ll + p_free * math.log(N),
"iterations": fit["iterations"], "converged": int(fit["converged"]), "starts": max(1, STARTS),
"starts_agree": fit["starts_agree"], "best_start": fit["start"]}
switches = 0
runs = {k: [] for k in range(K)}
for a, b in bounds:
r0 = a
for t in range(a + 1, b + 1):
if t == b or path[t] != path[t - 1]:
runs[int(path[t - 1])].append(t - r0)
if t < b:
switches += 1
r0 = t
values["switches"] = switches
state_names = [f"State {k + 1}" for k in range(K)]
rows = []
for k in range(K):
share = float(np.mean(path == k))
dur = 1.0 / (1.0 - A[k, k]) if A[k, k] < 1.0 else float("nan")
values[f"pi[{k + 1}]"] = float(pi0[k])
values[f"stationary[{k + 1}]"] = float(statd[k])
values[f"share[{k + 1}]"] = share
values[f"duration[{k + 1}]"] = dur
values[f"mean_run[{k + 1}]"] = float(np.mean(runs[k])) if runs[k] else float("nan")
row = {"state": state_names[k], "initial": float(pi0[k]), "stationary": float(statd[k]), "share": share,
"duration": dur, "mean_run": values[f"mean_run[{k + 1}]"]}
if family == "gaussian":
values[f"mean[{k + 1}]"] = float(par["mean"][k])
values[f"sd[{k + 1}]"] = float(math.sqrt(par["var"][k]))
row.update({"mean": float(par["mean"][k]), "sd": float(math.sqrt(par["var"][k]))})
elif family == "poisson":
values[f"rate[{k + 1}]"] = float(par["rate"][k])
row["rate"] = float(par["rate"][k])
else:
order = np.argsort(-par["prob"][k], kind="stable")[:3]
row["top"] = ", ".join(f"{levels[c]} ({par['prob'][k, c]:.2f})" for c in order)
for c in range(n_levels):
values[f"prob[{k + 1}:{levels[c]}]"] = float(par["prob"][k, c])
for j in range(K):
values[f"transition[{k + 1},{j + 1}]"] = float(A[k, j])
rows.append(row)
# %% Choosing the number of states
scan_rows = []
if SCAN:
for kk in range(1, SCAN_MAX + 1):
f_ = fit if kk == K else hmm.fit(seqs, family, kk, n_levels, SHARED_VAR, STARTS, SEED, MAX_ITER)
bic_ = -2 * f_["loglik"] + f_["n_params"] * math.log(N)
aic_ = -2 * f_["loglik"] + 2 * f_["n_params"]
scan_rows.append({"states": kk, "loglik": f_["loglik"], "params": f_["n_params"], "aic": aic_, "bic": bic_})
values[f"scan_loglik[{kk}]"] = f_["loglik"]
values[f"scan_aic[{kk}]"] = aic_
values[f"scan_bic[{kk}]"] = bic_
best = min(scan_rows, key=lambda r: r["bic"])
values["best_k_bic"] = best["states"]
for r in scan_rows:
r["best"] = "lowest BIC" if r["states"] == best["states"] else ""
# %% Assumptions
assumptions = [{"key": "markov", "label": "First-order Markov states", "status": "info",
"detail": "Assumed, not checked from the data: the next state depends only on the current one, the transition "
"probabilities stay the same over time, and each observation depends only on its state."}]
if max(1, STARTS) == 1:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "info",
"detail": "One start only: EM can stop at a local optimum; use several starts to check."})
elif fit["starts_agree"] >= 2:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "pass",
"detail": f"{fit['starts_agree']} of {max(1, STARTS)} starts reached the best log-likelihood ({ll:.4f})."})
else:
assumptions.append({"key": "stable_fit", "label": "Same optimum from different starts", "status": "warn",
"detail": f"Only start {fit['start']} of {max(1, STARTS)} reached the best log-likelihood ({ll:.4f}); the others stopped lower. "
"Add starts before trusting the states."})
# %% Charts
charts = []
first_n = bounds[0][1]
xs = labels[:first_n] if TIME else list(range(1, first_n + 1))
xkind = "temporal" if TEMPORAL else "numeric"
xname = TIME or "step"
first_title = f" ({SEQUENCE} {seq_names[0]})" if SEQUENCE and len(seqs) > 1 else ""
if family != "categorical":
charts.append(cs.chart("states", "segment-means", f"{VALUE} with the most probable states{first_title}", {
"x": cs.col(xname, xs, kind=xkind), "y": cs.col(VALUE, x_all[:first_n]),
"segment": cs.col("state", [state_names[int(s)] for s in path[:first_n]], kind="categorical")}))
if K > 1 and first_n <= 5000:
charts.append(cs.chart("posterior", "series-line", f"Probability of each state over time{first_title}", {
"x": cs.col(xname, [v for v in xs for _ in range(K)], kind=xkind),
"y": cs.col("probability", gamma[:first_n].reshape(-1)),
"group": cs.col("state", state_names * first_n, kind="categorical")}))
charts.append(cs.chart("transitions", "matrix-heatmap", "Transition probabilities (row = from, column = to)", {
"row": cs.col("from", [state_names[i] for i in range(K) for _ in range(K)], kind="categorical"),
"col": cs.col("to", [state_names[j] for _ in range(K) for j in range(K)], kind="categorical"),
"value": cs.col("probability", A.reshape(-1)),
"label": cs.col("text", [f"{v:.2f}" for v in A.reshape(-1)], kind="categorical")}))
if scan_rows:
charts.append(cs.chart("scan", "series-line", "Information criteria by number of states (lower is better)", {
"x": cs.col("states", [float(r["states"]) for r in scan_rows for _ in range(2)]),
"y": cs.col("criterion", [v for r in scan_rows for v in (r["aic"], r["bic"])]),
"group": cs.col("criterion name", ["AIC", "BIC"] * len(scan_rows), kind="categorical")}))
# %% Tables
state_cols = [{"key": "state", "label": "State", "type": "string"}]
if family == "gaussian":
state_cols += [{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}]
elif family == "poisson":
state_cols += [{"key": "rate", "label": "Rate", "type": "number"}]
else:
state_cols += [{"key": "top", "label": "Most likely values", "type": "string"}]
state_cols += [{"key": "initial", "label": "Initial probability", "type": "number"},
{"key": "stationary", "label": "Long-run share", "type": "percent"},
{"key": "share", "label": "Share of steps (most probable path)", "type": "percent"},
{"key": "duration", "label": "Expected stay (steps)", "type": "number"},
{"key": "mean_run", "label": "Mean run in path (steps)", "type": "number"}]
tables = [{"key": "states", "title": "States", "columns": state_cols, "rows": rows},
{"key": "transitions", "title": "Transition probabilities",
"columns": [{"key": "from", "label": "From", "type": "string"}] + [{"key": f"to{j + 1}", "label": f"To {state_names[j]}", "type": "number"} for j in range(K)],
"rows": [{"from": state_names[i], **{f"to{j + 1}": float(A[i, j]) for j in range(K)}} for i in range(K)]}]
if family == "categorical":
tables.append({"key": "emissions", "title": "Emission probabilities",
"columns": [{"key": "state", "label": "State", "type": "string"}] + [{"key": f"c{c + 1}", "label": levels[c], "type": "number"} for c in range(n_levels)],
"rows": [{"state": state_names[k], **{f"c{c + 1}": float(par["prob"][k, c]) for c in range(n_levels)}} for k in range(K)]})
if scan_rows:
tables.append({"key": "scan", "title": "Choosing the number of states",
"columns": [{"key": "states", "label": "States", "type": "integer"}, {"key": "loglik", "label": "Log-likelihood", "type": "number"},
{"key": "params", "label": "Parameters", "type": "integer"}, {"key": "aic", "label": "AIC", "type": "number"},
{"key": "bic", "label": "BIC", "type": "number"}, {"key": "best", "label": "", "type": "string"}],
"rows": scan_rows})
CAP = 2000
shown = min(N, CAP)
path_rows = []
for i in range(shown):
path_rows.append({"sequence": seq_ids[i], "time": str(labels[i]) if TIME else str(int(step[i])),
"value": levels[int(x_all[i])] if family == "categorical" else float(x_all[i]),
"state": state_names[int(path[i])], "posterior": float(gamma[i, int(path[i])])})
tables.append({"key": "path", "title": "Most probable state of each step" + (f" (first {CAP} of {N})" if N > CAP else ""),
"columns": ([{"key": "sequence", "label": SEQUENCE, "type": "string"}] if SEQUENCE else [])
+ [{"key": "time", "label": TIME or "Step", "type": "string"},
{"key": "value", "label": VALUE, "type": "string" if family == "categorical" else "number"},
{"key": "state", "label": "State", "type": "string"},
{"key": "posterior", "label": "Probability of that state", "type": "number"}],
"rows": path_rows})
# %% Result
fam_label = {"gaussian": "Gaussian", "poisson": "Poisson", "categorical": "categorical"}[family]
where = f" over {len(seqs)} sequences" if len(seqs) > 1 else ""
if family == "gaussian":
desc = "; ".join(f"{state_names[k]} mean {par['mean'][k]:.4g} (stay {values[f'duration[{k + 1}]']:.3g} steps)" for k in range(K))
elif family == "poisson":
desc = "; ".join(f"{state_names[k]} rate {par['rate'][k]:.4g} (stay {values[f'duration[{k + 1}]']:.3g} steps)" for k in range(K))
else:
desc = "; ".join(f"{state_names[k]} mostly {levels[int(np.argmax(par['prob'][k]))]}" for k in range(K))
summary = f"A {K}-state hidden Markov model with {fam_label} emissions for {VALUE} ({N} steps{where}): {desc}. Log-likelihood {ll:.2f}, BIC {values['bic']:.1f}."
if not fit["converged"]:
warnings.append(cs.cs_warning("CS_W_NO_CONVERGENCE", what="The EM fit of the hidden Markov model"))
notes = [f"EM (Baum–Welch) from {max(1, STARTS)} start(s): one deterministic (equal-count groups of the sorted values, even transitions) and the rest from seed {SEED}; "
f"the best log-likelihood is kept. States are numbered by increasing "
+ ("mean" if family == "gaussian" else "rate" if family == "poisson" else "probability of the most common value, reversed") + ", so labels don't switch between runs.",
"Each state lasts a geometric number of steps (expected stay 1 / (1 − stay probability)); if real regimes last a typical length, the model will split or merge them.",
"The most probable path (Viterbi) is the single best sequence of states; the state probabilities show how sure the model is at each step."]
statistics = [{"key": "loglik", "label": "Log-likelihood", "value": ll}, {"key": "bic", "label": "BIC", "value": values["bic"]},
{"key": "aic", "label": "AIC", "value": values["aic"]}]
cs.publish({
"method": "ts.hmm",
"methodVersion": "1.0.0",
"title": "Hidden Markov model",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": N,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
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.
Stays and long-run shares
ExploreThe 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?
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 to see the result.
Raise P(stay in A) toward 1: stays in A grow like 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.
What an HMM assumes
Read- Geometric stays. A state lasts 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.
Networks: one role, or a mix?
ReadA 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.
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
View data
| With block | Block | Link probability |
|---|---|---|
| Block 1 | Block 1 | 0.0121 |
| Block 2 | Block 1 | 0.3154 |
| Block 1 | Block 2 | 0.3154 |
| Block 2 | Block 2 | 0.8444 |
Higher is better; BIC chose 2 blocks.
View data
| Best | Criterion | Blocks | Criterion |
|---|---|---|---|
| false | ICL | 1 | −489.40 |
| true | ICL | 2 | −348.54 |
| false | ICL | 3 | −376.59 |
| false | ICL | 4 | −380.27 |
| false | BIC | 1 | −489.40 |
| true | BIC | 2 | −348.54 |
| false | BIC | 3 | −359.65 |
| false | BIC | 4 | −376.32 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | c01 | 30 | 0 | 1 |
| 2 | 2 | c02 | 43 | 0 | 1 |
| 3 | 2 | c03 | 22 | 0 | 1 |
| 4 | 2 | c04 | 23 | 0 | 1 |
| 5 | 2 | c05 | 31 | 0 | 1 |
| 6 | 2 | c06 | 12 | 0 | 1 |
| 7 | 2 | c07 | 25 | 0 | 1 |
| 8 | 2 | c08 | 32 | 0 | 1 |
| 9 | 2 | c09 | 40 | 0 | 1 |
| 10 | 2 | c10 | 45 | 0 | 1 |
| 12 | 1 | p01 | 46 | 0 | 1 |
| 14 | 1 | p02 | 47 | 0 | 1 |
| 15 | 1 | p03 | 48 | 0 | 1 |
| 16 | 1 | p04 | 17 | 0 | 1 |
| 17 | 1 | p05 | 18 | 0 | 1 |
| 19 | 1 | p06 | 24 | 0 | 1 |
| 23 | 1 | p08 | 26 | 0 | 1 |
| 25 | 1 | p09 | 33 | 0 | 1 |
| 30 | 1 | p10 | 35 | 0 | 1 |
| 31 | 1 | p11 | 44 | 0 | 1 |
| 32 | 1 | p12 | 10 | 0 | 1 |
| 33 | 1 | p13 | 11 | 0 | 1 |
| 34 | 1 | p14 | 14 | 0 | 1 |
| 35 | 1 | p15 | 16 | 0 | 1 |
| 36 | 1 | p16 | 19 | 0 | 1 |
| 39 | 1 | p17 | 21 | 0 | 1 |
| 47 | 1 | p18 | 41 | 0 | 1 |
| 2 | 1 | p19 | 15 | 1 | 1 |
| 3 | 1 | p20 | 20 | 1 | 1 |
| 4 | 1 | p21 | 27 | 1 | 1 |
| 5 | 1 | p22 | 34 | 1 | 1 |
| 6 | 1 | p23 | 38 | 1 | 1 |
| 8 | 1 | p24 | 39 | 1 | 1 |
| 9 | 1 | p25 | 42 | 1 | 1 |
| 11 | 1 | p26 | 13 | 1 | 1 |
| 18 | 1 | p27 | 28 | 1 | 1 |
| 19 | 1 | p28 | 29 | 1 | 1 |
| 21 | 1 | p29 | 36 | 1 | 1 |
| 22 | 1 | p30 | 37 | 1 | 1 |
| 25 | 1 | p31 | 0 | 1 | 1 |
| 32 | 1 | p32 | 1 | 1 | 1 |
| 40 | 1 | p33 | 5 | 1 | 1 |
| 41 | 1 | p34 | 2 | 1 | 1 |
| 42 | 1 | p35 | 4 | 1 | 1 |
| 43 | 1 | p36 | 9 | 1 | 1 |
| 45 | 1 | p37 | 7 | 1 | 1 |
| 46 | 1 | p38 | 3 | 1 | 1 |
| 48 | 1 | p39 | 6 | 1 | 1 |
| 4 | 1 | p40 | 8 | 2 | 1 |
| 5 | — | — | — | 2 | 1 |
| 6 | — | — | — | 2 | 1 |
| 7 | — | — | — | 2 | 1 |
| 8 | — | — | — | 2 | 1 |
| 11 | — | — | — | 2 | 1 |
| 12 | — | — | — | 2 | 1 |
| 13 | — | — | — | 2 | 1 |
| 14 | — | — | — | 2 | 1 |
| 17 | — | — | — | 2 | 1 |
| 23 | — | — | — | 2 | 1 |
| 24 | — | — | — | 2 | 1 |
First 60 of 170 rows.
View data
| From | Block | Node | Degree | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | c01 | 27 | 1 | 0.0647 | 0.2206 |
| 0 | 2 | c02 | 22 | 2 | −0.0703 | −0.0522 |
| 0 | 2 | c03 | 21 | 3 | 0.0556 | −0.2756 |
| 0 | 2 | c04 | 17 | 4 | 0.0011 | 0.1048 |
| 0 | 2 | c05 | 21 | 5 | −0.2148 | −0.0705 |
| 0 | 2 | c06 | 22 | 6 | 0.0092 | −0.1142 |
| 0 | 2 | c07 | 16 | 7 | 0.1814 | 0.0672 |
| 0 | 2 | c08 | 19 | 8 | 0.2416 | −0.1651 |
| 0 | 2 | c09 | 14 | 9 | −0.0366 | −0.1490 |
| 0 | 2 | c10 | 20 | 10 | −0.2293 | 0.1655 |
| 0 | 1 | p01 | 3 | 12 | −0.3715 | 0.6393 |
| 0 | 1 | p02 | 3 | 14 | −0.4997 | −0.1871 |
| 0 | 1 | p03 | 5 | 15 | 0.1987 | −0.2454 |
| 0 | 1 | p04 | 1 | 16 | 0.1736 | −1 |
| 0 | 1 | p05 | 3 | 17 | 0.1100 | −0.4102 |
| 0 | 1 | p06 | 2 | 19 | 0.4894 | 0.5501 |
| 0 | 1 | p08 | 3 | 23 | −0.5082 | 0.3244 |
| 0 | 1 | p09 | 4 | 25 | 0.5402 | −0.0508 |
| 0 | 1 | p10 | 4 | 30 | 0.4464 | 0.0612 |
| 0 | 1 | p11 | 3 | 31 | 0.0994 | 0.5200 |
| 0 | 1 | p12 | 2 | 32 | −0.3263 | −0.4763 |
| 0 | 1 | p13 | 3 | 33 | −0.4702 | −0.3604 |
| 0 | 1 | p14 | 6 | 34 | 0.1060 | −0.0352 |
| 0 | 1 | p15 | 6 | 35 | 0.2189 | 0.1485 |
| 0 | 1 | p16 | 4 | 36 | −0.3539 | −0.0189 |
| 0 | 1 | p17 | 5 | 39 | −0.1623 | 0.3314 |
| 0 | 1 | p18 | 4 | 47 | 0.1637 | −0.5505 |
| 1 | 1 | p19 | 2 | 2 | −0.1921 | 0.6509 |
| 1 | 1 | p20 | 1 | 3 | −0.9067 | −0.2940 |
| 1 | 1 | p21 | 1 | 4 | −0.8718 | 0.4965 |
| 1 | 1 | p22 | 8 | 5 | −0.0443 | 0.0333 |
| 1 | 1 | p23 | 6 | 6 | −0.2952 | 0.1515 |
| 1 | 1 | p24 | 5 | 8 | 0.3638 | 0.2121 |
| 1 | 1 | p25 | 4 | 9 | −0.4595 | 0.1276 |
| 1 | 1 | p26 | 2 | 11 | 0.5505 | 0.2952 |
| 1 | 1 | p27 | 4 | 18 | 0.3660 | −0.1414 |
| 1 | 1 | p28 | 1 | 19 | 0.3536 | 0.8868 |
| 1 | 1 | p29 | 1 | 21 | 0.8376 | −0.5543 |
| 1 | 1 | p30 | 2 | 22 | 0.7614 | −0.1230 |
| 1 | 1 | p31 | 2 | 25 | −0.1585 | 0.8464 |
| 1 | 1 | p32 | 5 | 32 | −0.3514 | 0.4490 |
| 1 | 1 | p33 | 3 | 40 | −0.1077 | −0.5990 |
| 1 | 1 | p34 | 2 | 41 | 0.2435 | −0.6710 |
| 1 | 1 | p35 | 7 | 42 | −0.0037 | 0.3144 |
| 1 | 1 | p36 | 4 | 43 | 0.3518 | −0.3309 |
| 1 | 1 | p37 | 5 | 45 | −0.1879 | −0.3302 |
| 1 | 1 | p38 | 5 | 46 | −0.0777 | −0.3903 |
| 1 | 1 | p39 | 5 | 48 | 0.2471 | 0.2456 |
| 2 | 1 | p40 | 5 | 4 | −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
| Block | Nodes | Model share | Link probability within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 39 | 79.6% | 0.0121 | 1.0000 | p22, p35, p14 |
| 2 | 10 | 20.4% | 0.8444 | 1.0000 | c01, c02, c06 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.3154 |
| Block 2 | 0.3154 | 0.8444 |
Number of blocks
| Blocks | ICL | BIC | Lower 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
))
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
| Block | Nodes | Model share | Link probability within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 39 | 79.6% | 0.0121 | 1.0000 | p22, p35, p14 |
| 2 | 10 | 20.4% | 0.8444 | 1.0000 | c01, c02, c06 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.3154 |
| Block 2 | 0.3154 | 0.8444 |
Number of blocks
| Blocks | ICL | BIC | Lower 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.
Mixed memberships
ReadPeople 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 (a Dirichlet draw). For each ordered pair, the sender picks a role from and the receiver from ; a link appears with the block matrix's probability. Averaged over roles,
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.
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.
Check: HMMs and blockmodels
CheckpointCheck yourself
A state stays put with probability each step. What is its expected stay, in steps?
Show the answer
Answer: 5
.
Check yourself
Why does the forward algorithm make HMM likelihoods practical?
Show the answer
Answer: a
There are paths, but the recursion needs only 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 . Node has and node has . What is ?
Show the answer
Answer: 0.5
, and .
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.
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