Blocks and biclusters: models for who links with whom, and rows that agree on some columns
Stochastic blockmodels explain a network with block-to-block link probabilities; degree correction stops hubs from forming their own block. Cheng–Church, spectral co-clustering and spectral biclustering cluster rows and columns together.
What runs in CodeSplash
- UCL034Stochastic block model (SBM) Runs in CodeSplash (Experimental)
- UCL035Degree-corrected stochastic block model Runs in CodeSplash (Experimental)
- UCL036Cheng–Church biclustering Runs in CodeSplash
- UCL037Spectral co-clustering Runs in CodeSplash
- UCL038Spectral biclustering Runs in CodeSplash
- Stochastic blockmodel Experimental
- Biclustering (rows × columns) Verified in Python and R
You will be able to
- Write the stochastic blockmodel and say what a block means (not always a community)
- Explain what degree correction adds and when it can overfit
- Read a mean squared residue and say why a tiny bicluster can score well
- Choose between overlapping biclusters, one-to-one co-clusters and a checkerboard
Generative models for structure
ReadThe last lesson's graph methods optimize a score. A blockmodel goes further: it is a probability model that could have generated the network. That buys a likelihood, criteria to choose the number of blocks, and a way to check the fit by simulating graphs from it.
Biclustering asks a related question of a table: which rows and columns belong together? A group of customers may agree on some products and ignore the rest, which row clustering alone can't show.
The stochastic blockmodel
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. gives each node a block and links each pair independently with a probability that depends only on their blocks: .
Blocks are groups of nodes that link alike, which is broader than communities. A core–periphery network, where the core links to everyone and the periphery only to the core, is a two-block model with no community in sight.
The stochastic blockmodel puts 37 nodes in 2 blocks (chosen by ICL); the average node sits in its block with probability 0.977.
- Blocks
- 2
- ICL
- −279.52
- Mean certainty
- 0.9769
Plots
View data
| With block | Block | Link probability |
|---|---|---|
| Block 1 | Block 1 | 0.2039 |
| Block 2 | Block 1 | 0.0397 |
| Block 1 | Block 2 | 0.0397 |
| Block 2 | Block 2 | 0.3754 |
Higher is better; ICL chose 2 blocks.
View data
| Best | Criterion | Blocks | Criterion |
|---|---|---|---|
| false | ICL | 1 | −281.46 |
| true | ICL | 2 | −279.52 |
| false | ICL | 3 | −288.60 |
| false | ICL | 4 | −296.75 |
| false | ICL | 5 | −310.46 |
| false | BIC | 1 | −281.46 |
| true | BIC | 2 | −277.45 |
| false | BIC | 3 | −284.83 |
| false | BIC | 4 | −294.21 |
| false | BIC | 5 | −308.17 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 5 | 1 | p01 | 2 | 0 | 2 |
| 6 | 1 | p02 | 11 | 0 | 1 |
| 11 | 1 | p03 | 29 | 0 | 1 |
| 15 | 1 | p04 | 5 | 0 | 1 |
| 32 | 1 | p05 | 24 | 0 | 1 |
| 2 | 1 | p06 | 27 | 1 | 1 |
| 3 | 1 | p07 | 33 | 1 | 1 |
| 4 | 1 | p08 | 1 | 1 | 1 |
| 5 | 1 | p09 | 9 | 1 | 1 |
| 9 | 1 | p10 | 28 | 1 | 1 |
| 11 | 1 | p11 | 30 | 1 | 1 |
| 5 | 1 | p12 | 0 | 2 | 1 |
| 6 | 2 | p13 | 3 | 2 | 1 |
| 8 | 2 | p14 | 7 | 2 | 1 |
| 9 | 2 | p15 | 35 | 2 | 1 |
| 10 | 2 | p16 | 4 | 2 | 1 |
| 21 | 2 | p17 | 8 | 2 | 1 |
| 33 | 2 | p18 | 25 | 2 | 1 |
| 35 | 2 | p19 | 26 | 2 | 1 |
| 7 | 2 | p20 | 31 | 3 | 1 |
| 8 | 2 | p21 | 34 | 3 | 1 |
| 9 | 2 | p22 | 6 | 3 | 1 |
| 29 | 2 | p23 | 10 | 3 | 1 |
| 6 | 2 | p24 | 36 | 4 | 1 |
| 8 | 1 | p25 | 20 | 4 | 1 |
| 9 | 1 | p26 | 14 | 4 | 1 |
| 7 | 1 | p27 | 15 | 5 | 1 |
| 9 | 1 | p28 | 19 | 5 | 1 |
| 26 | 1 | p29 | 22 | 5 | 1 |
| 31 | 1 | p30 | 12 | 5 | 1 |
| 9 | 1 | p31 | 32 | 7 | 1 |
| 11 | 1 | p32 | 18 | 7 | 1 |
| 24 | 2 | p33 | 23 | 7 | 1 |
| 11 | 1 | p34 | 16 | 8 | 1 |
| 11 | 1 | p35 | 21 | 10 | 1 |
| 15 | 1 | p36 | 13 | 11 | 1 |
| 28 | 1 | p37 | 17 | 11 | 1 |
| 30 | — | — | — | 11 | 1 |
| 16 | — | — | — | 12 | 1 |
| 17 | — | — | — | 12 | 1 |
| 18 | — | — | — | 12 | 1 |
| 19 | — | — | — | 12 | 1 |
| 22 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 19 | — | — | — | 13 | 1 |
| 23 | — | — | — | 13 | 1 |
| 15 | — | — | — | 14 | 1 |
| 16 | — | — | — | 14 | 1 |
| 18 | — | — | — | 14 | 1 |
| 19 | — | — | — | 14 | 1 |
| 20 | — | — | — | 14 | 1 |
| 22 | — | — | — | 14 | 1 |
| 23 | — | — | — | 14 | 1 |
| 18 | — | — | — | 15 | 1 |
| 19 | — | — | — | 15 | 1 |
| 20 | — | — | — | 15 | 1 |
| 22 | — | — | — | 15 | 1 |
| 21 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 20 | — | — | — | 17 | 1 |
First 60 of 98 rows.
View data
| From | Block | Node | Degree | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 1 | p01 | 5 | 5 | 0.0528 | −0.1113 |
| 0 | 1 | p02 | 6 | 6 | −0.1108 | −0.2932 |
| 0 | 1 | p03 | 9 | 11 | −0.0906 | −0.1818 |
| 0 | 1 | p04 | 5 | 15 | −0.1865 | −0.2168 |
| 0 | 1 | p05 | 4 | 32 | −0.0736 | −0.4174 |
| 1 | 1 | p06 | 7 | 2 | −0.0193 | −0.2355 |
| 1 | 1 | p07 | 3 | 3 | 0.0363 | −0.3021 |
| 1 | 1 | p08 | 5 | 4 | −0.1432 | −0.2178 |
| 1 | 1 | p09 | 4 | 5 | −0.1008 | −0.3271 |
| 1 | 1 | p10 | 6 | 9 | −0.1547 | −0.3225 |
| 1 | 1 | p11 | 2 | 11 | −0.0172 | −0.3266 |
| 2 | 1 | p12 | 8 | 5 | −0.0373 | −0.1676 |
| 2 | 2 | p13 | 6 | 6 | −0.0318 | 0.3014 |
| 2 | 2 | p14 | 2 | 8 | 0.1659 | 0.3608 |
| 2 | 2 | p15 | 7 | 9 | −0.0317 | 0.2386 |
| 2 | 2 | p16 | 7 | 10 | −0.0150 | 0.0763 |
| 2 | 2 | p17 | 4 | 21 | −0.1295 | 0.2473 |
| 2 | 2 | p18 | 2 | 33 | 0.0332 | 0.3246 |
| 2 | 2 | p19 | 5 | 35 | −0.1118 | 0.1693 |
| 3 | 2 | p20 | 7 | 7 | 0.0563 | 0.2119 |
| 3 | 2 | p21 | 8 | 8 | −0.0529 | 0.1429 |
| 3 | 2 | p22 | 4 | 9 | −0.1447 | 0.0531 |
| 3 | 2 | p23 | 7 | 29 | −0.0048 | 0.1757 |
| 4 | 2 | p24 | 5 | 6 | 0.0899 | 0.2836 |
| 4 | 1 | p25 | 7 | 8 | −0.1131 | −0.0468 |
| 4 | 1 | p26 | 4 | 9 | 0.0675 | 0.0410 |
| 5 | 1 | p27 | 4 | 7 | 0.1215 | −0.1360 |
| 5 | 1 | p28 | 7 | 9 | −0.0003 | −0.0382 |
| 5 | 1 | p29 | 6 | 26 | −0.0658 | −0.0729 |
| 5 | 1 | p30 | 8 | 31 | −0.0631 | −0.0016 |
| 7 | 1 | p31 | 6 | 9 | 0.0574 | −0.0253 |
| 7 | 1 | p32 | 4 | 11 | −0.0036 | −0.1266 |
| 7 | 2 | p33 | 6 | 24 | 0.0496 | 0.0970 |
| 8 | 1 | p34 | 7 | 11 | 0.0035 | −0.0038 |
| 10 | 1 | p35 | 4 | 11 | 0.1282 | −0.0237 |
| 11 | 1 | p36 | 5 | 15 | −0.1602 | −0.0175 |
| 11 | 1 | p37 | 0 | 28 | 1 | 0.8885 |
| 11 | — | — | — | 30 | — | — |
| 12 | — | — | — | 16 | — | — |
| 12 | — | — | — | 17 | — | — |
| 12 | — | — | — | 18 | — | — |
| 12 | — | — | — | 19 | — | — |
| 12 | — | — | — | 22 | — | — |
| 12 | — | — | — | 23 | — | — |
| 13 | — | — | — | 19 | — | — |
| 13 | — | — | — | 23 | — | — |
| 14 | — | — | — | 15 | — | — |
| 14 | — | — | — | 16 | — | — |
| 14 | — | — | — | 18 | — | — |
| 14 | — | — | — | 19 | — | — |
| 14 | — | — | — | 20 | — | — |
| 14 | — | — | — | 22 | — | — |
| 14 | — | — | — | 23 | — | — |
| 15 | — | — | — | 18 | — | — |
| 15 | — | — | — | 19 | — | — |
| 15 | — | — | — | 20 | — | — |
| 15 | — | — | — | 22 | — | — |
| 16 | — | — | — | 21 | — | — |
| 16 | — | — | — | 22 | — | — |
| 17 | — | — | — | 20 | — | — |
First 60 of 98 rows.
Blocks
| Block | Nodes | Model share | Link probability within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 24 | 65.8% | 0.2039 | 0.9895 | p03, p12, p30 |
| 2 | 13 | 34.2% | 0.3754 | 0.9538 | p21, p15, p16 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.2039 | 0.0397 |
| Block 2 | 0.0397 | 0.3754 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −281.46 | −281.46 | −278.21 |
| 2 | −279.52 | −277.45 | −265.89 |
| 3 | −288.60 | −284.83 | −261.72 |
| 4 | −296.75 | −294.21 | −256.29 |
| 5 | −310.46 | −308.17 | −252.19 |
- 1 of 101 rows were left out because a value was missing.
- 1 edge(s) join a node to itself; measures on the simple network leave them out.
- 1 edge(s) repeat a pair listed earlier; the simple network merges them and adds their weights.
- 2 of 38 node table rows were left out: the node id was missing or listed earlier.
- 1 node id(s) in the edge list aren't in the node table, so their attributes are missing.
- 1 node(s) have no edges to other nodes.
- The network has 2 separate parts; the largest has 36 of 37 nodes.
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 073401e2736d9cd4
# Dataset: graph_blocks_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 <- 5
CRITERION <- "icl"
STARTS <- 5L
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/blocks_bernoulli/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 37 nodes in 2 blocks (chosen by ICL); the average node sits in its block with probability 0.977.
- Blocks
- 2
- ICL
- −279.52
- Mean certainty
- 0.9769
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 | 24 | 65.8% | 0.2039 | 0.9895 | p03, p12, p30 |
| 2 | 13 | 34.2% | 0.3754 | 0.9538 | p21, p15, p16 |
Link probability between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.2039 | 0.0397 |
| Block 2 | 0.0397 | 0.3754 |
Number of blocks
| Blocks | ICL | BIC | Lower bound |
|---|---|---|---|
| 1 | −281.46 | −281.46 | −278.21 |
| 2 | −279.52 | −277.45 | −265.89 |
| 3 | −288.60 | −284.83 | −261.72 |
| 4 | −296.75 | −294.21 | −256.29 |
| 5 | −310.46 | −308.17 | −252.19 |
- 1 of 101 rows were left out because a value was missing.
- 1 edge(s) join a node to itself; measures on the simple network leave them out.
- 1 edge(s) repeat a pair listed earlier; the simple network merges them and adds their weights.
- 2 of 38 node table rows were left out: the node id was missing or listed earlier.
- 1 node id(s) in the edge list aren't in the node table, so their attributes are missing.
- 1 node(s) have no edges to other nodes.
- The network has 2 separate parts; the largest has 36 of 37 nodes.
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 073401e2736d9cd4
# Dataset: graph_blocks_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 = 5
CRITERION = "icl"
STARTS = 5
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/blocks_bernoulli/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 the criterion chose 2 blocks. The likelihood always rises with more blocks, so the choice uses a penalty (ICL or BIC), not the raw likelihood.
Hubs in a plain blockmodel
PredictPredict first
A club's network has two social groups, each with a couple of very popular members. A plain blockmodel with two blocks can split it two ways. Which is it prone to?
Reveal
By degree. Inside a block, a plain blockmodel expects every node to have about the same number of links, so a few hubs can look like a block of their own. Degree correction removes that pull.
Degree correction
ReadThe degree-corrected blockmodelDegree-corrected blockmodelA blockmodel whose link counts scale with both nodes' degrees, so hubs share a block with nodes that link to the same places. gives each node its own propensity : . Popular nodes link more without needing a block of their own; describes the blocks.
The degree-corrected blockmodel puts 34 nodes in 2 blocks (as set); the average node sits in its block with probability 0.964.
- Blocks
- 2
- ICL
- −198.48
- Mean certainty
- 0.9636
Plots
View data
| With block | Block | Rate per degree pair (λ) |
|---|---|---|
| Block 1 | Block 1 | 0.0121 |
| Block 2 | Block 1 | 0.0018 |
| Block 1 | Block 2 | 0.0018 |
| Block 2 | Block 2 | 0.0123 |
Nodes sorted by block: each tile of the matrix is one pair of blocks.
View data
| Column | Block | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 1 |
| 2 | 2 | 1 | 26 | 0 | 1 |
| 3 | 2 | 10 | 25 | 0 | 1 |
| 4 | 2 | 11 | 16 | 0 | 1 |
| 5 | 2 | 12 | 32 | 0 | 1 |
| 9 | 2 | 13 | 20 | 0 | 1 |
| 11 | 1 | 14 | 22 | 0 | 1 |
| 12 | 1 | 15 | 24 | 0 | 1 |
| 14 | 2 | 16 | 17 | 0 | 1 |
| 23 | 2 | 17 | 18 | 0 | 1 |
| 25 | 1 | 18 | 21 | 0 | 1 |
| 28 | 2 | 19 | 6 | 0 | 1 |
| 29 | 2 | 2 | 7 | 0 | 1 |
| 30 | 1 | 20 | 10 | 0 | 1 |
| 31 | 2 | 21 | 13 | 0 | 1 |
| 32 | 1 | 22 | 15 | 0 | 1 |
| 5 | 1 | 23 | 19 | 1 | 1 |
| 9 | 1 | 24 | 33 | 1 | 1 |
| 11 | 1 | 25 | 0 | 1 | 1 |
| 12 | 1 | 26 | 12 | 1 | 1 |
| 14 | 1 | 27 | 1 | 1 | 1 |
| 23 | 1 | 28 | 23 | 1 | 1 |
| 24 | 1 | 29 | 5 | 1 | 1 |
| 31 | 2 | 3 | 29 | 1 | 1 |
| 28 | 1 | 30 | 30 | 2 | 1 |
| 29 | 1 | 31 | 31 | 2 | 1 |
| 23 | 1 | 32 | 2 | 4 | 1 |
| 12 | 1 | 33 | 11 | 5 | 1 |
| 23 | 2 | 4 | 28 | 5 | 1 |
| 27 | 2 | 5 | 4 | 5 | 1 |
| 26 | 2 | 6 | 8 | 6 | 1 |
| 27 | 2 | 7 | 9 | 6 | 1 |
| 26 | 1 | 8 | 14 | 7 | 1 |
| 27 | 1 | 9 | 3 | 7 | 1 |
| 29 | — | — | — | 8 | 1 |
| 30 | — | — | — | 8 | 1 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 1 |
| 21 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 26 | — | — | — | 12 | 1 |
| 31 | — | — | — | 12 | 1 |
| 32 | — | — | — | 12 | 1 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 1 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 1 |
| 27 | — | — | — | 15 | 1 |
| 18 | — | — | — | 16 | 1 |
| 20 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 26 | — | — | — | 16 | 1 |
| 27 | — | — | — | 16 | 1 |
| 18 | — | — | — | 17 | 1 |
| 20 | — | — | — | 17 | 1 |
| 25 | — | — | — | 17 | 1 |
| 25 | — | — | — | 18 | 1 |
| 22 | — | — | — | 19 | 1 |
First 60 of 78 rows.
View data
| From | Block | Node | Degree | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 16 | 1 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 9 | 2 | −0.2233 | −0.0757 |
| 0 | 2 | 10 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 1 | 4 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 2 | 5 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 5 | 9 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 2 | 11 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 2 | 12 | 0.5571 | −0.0469 |
| 0 | 2 | 16 | 2 | 14 | −0.5525 | −1 |
| 0 | 2 | 17 | 2 | 23 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 2 | 25 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 3 | 28 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 10 | 29 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 2 | 30 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 2 | 31 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 2 | 32 | 0.6464 | 0.3546 |
| 1 | 1 | 23 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 1 | 24 | 3 | 9 | −0.0504 | 0.6329 |
| 1 | 1 | 25 | 3 | 11 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 2 | 12 | 0.6203 | 0.5661 |
| 1 | 1 | 27 | 4 | 14 | 0.1293 | 0.4353 |
| 1 | 1 | 28 | 3 | 23 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 4 | 24 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 6 | 31 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 4 | 28 | 0.2164 | −0.0296 |
| 2 | 1 | 31 | 6 | 29 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 12 | 23 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 17 | 12 | 0.3249 | 0.2115 |
| 5 | 2 | 4 | 3 | 23 | −0.4335 | −0.5876 |
| 5 | 2 | 5 | 4 | 27 | −0.5362 | −0.7094 |
| 6 | 2 | 6 | 4 | 26 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 4 | 27 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 5 | 26 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 2 | 27 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | — | — |
| 8 | — | — | — | 30 | — | — |
| 10 | — | — | — | 26 | — | — |
| 10 | — | — | — | 27 | — | — |
| 11 | — | — | — | 27 | — | — |
| 12 | — | — | — | 20 | — | — |
| 12 | — | — | — | 21 | — | — |
| 12 | — | — | — | 23 | — | — |
| 12 | — | — | — | 26 | — | — |
| 12 | — | — | — | 31 | — | — |
| 12 | — | — | — | 32 | — | — |
| 12 | — | — | — | 33 | — | — |
| 13 | — | — | — | 26 | — | — |
| 13 | — | — | — | 27 | — | — |
| 15 | — | — | — | 26 | — | — |
| 15 | — | — | — | 27 | — | — |
| 16 | — | — | — | 18 | — | — |
| 16 | — | — | — | 20 | — | — |
| 16 | — | — | — | 22 | — | — |
| 16 | — | — | — | 26 | — | — |
| 16 | — | — | — | 27 | — | — |
| 17 | — | — | — | 18 | — | — |
| 17 | — | — | — | 20 | — | — |
| 17 | — | — | — | 25 | — | — |
| 18 | — | — | — | 25 | — | — |
| 19 | — | — | — | 22 | — | — |
First 60 of 78 rows.
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 51.6% | 0.0121 | 0.9527 | 33, 32, 31 |
| 2 | 16 | 48.4% | 0.0123 | 0.9759 | 0, 2, 1 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.0018 |
| Block 2 | 0.0018 | 0.0123 |
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 6194fdf6c90dc39b
# Dataset: graph_karate (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 <- "poisson_dc"
BLOCKS <- 2
MAX_BLOCKS <- 6
CRITERION <- "icl"
STARTS <- 5L
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/karate_dc/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 degree-corrected blockmodel puts 34 nodes in 2 blocks (as set); the average node sits in its block with probability 0.964.
- Blocks
- 2
- ICL
- −198.48
- Mean certainty
- 0.9636
To keep this page light, the plots are shown once, under the R tab.
Blocks
| Block | Nodes | Model share | Rate per degree pair (λ) within | Mean certainty | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 18 | 51.6% | 0.0121 | 0.9527 | 33, 32, 31 |
| 2 | 16 | 48.4% | 0.0123 | 0.9759 | 0, 2, 1 |
Rate per degree pair (λ) between blocks
| Block | Block 1 | Block 2 |
|---|---|---|
| Block 1 | 0.0121 | 0.0018 |
| Block 2 | 0.0018 | 0.0123 |
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 6194fdf6c90dc39b
# Dataset: graph_karate (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 = "poisson_dc"
BLOCKS = 2
MAX_BLOCKS = 6
CRITERION = "icl"
STARTS = 5
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/karate_dc/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,
})
On the karate club its two blocks match the club's real split with an adjusted Rand index of 0.882. The extra parameters can also overfit small groups, and a Poisson model of counts isn't the same as a model of yes/no links. Compare the two models with a penalty or held-out edges.
Cheng–Church: coherent submatrices
ReadCheng–Church looks for a set of rows and columns that move in parallel. Its score is the mean squared residue
what's left after removing row, column and overall means inside the block. It greedily deletes and adds rows and columns until is below a threshold , masks the block and searches again.
3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.
- Biclusters
- 3
- Rows covered
- 36.7%
- Mean squared residue
- 0.0092
Plots
View data
| Bicluster | Column | Row | Value (standardized) |
|---|---|---|---|
| -1 | x1 | r01 | 1.166 |
| -1 | x2 | r01 | −0.1202 |
| -1 | x3 | r01 | 0.2679 |
| -1 | x4 | r01 | 0.6042 |
| -1 | x5 | r01 | −0.9826 |
| -1 | x6 | r01 | 0.0277 |
| -1 | x7 | r01 | 0.4645 |
| -1 | x8 | r01 | −0.0677 |
| -1 | x9 | r01 | 2.850 |
| -1 | x10 | r01 | 0.2368 |
| -1 | x11 | r01 | −0.4948 |
| -1 | x12 | r01 | −0.1775 |
| -1 | x1 | r02 | 0.0436 |
| -1 | x2 | r02 | −1.401 |
| -1 | x3 | r02 | −0.6471 |
| -1 | x4 | r02 | −0.3771 |
| -1 | x5 | r02 | 0.8307 |
| -1 | x6 | r02 | −0.0856 |
| -1 | x7 | r02 | 0.6873 |
| -1 | x8 | r02 | 1.283 |
| -1 | x9 | r02 | 0.9333 |
| -1 | x10 | r02 | −1.728 |
| -1 | x11 | r02 | −0.5257 |
| -1 | x12 | r02 | −1.081 |
| 2 | x1 | r03 | 0.8580 |
| 2 | x2 | r03 | −0.5201 |
| 2 | x3 | r03 | 0.0291 |
| 2 | x4 | r03 | 0.3487 |
| 2 | x5 | r03 | 0.0055 |
| -1 | x6 | r03 | −0.5167 |
| -1 | x7 | r03 | −1.908 |
| -1 | x8 | r03 | −0.4464 |
| -1 | x9 | r03 | 1.701 |
| -1 | x10 | r03 | 0.1065 |
| -1 | x11 | r03 | −0.3729 |
| -1 | x12 | r03 | 1.107 |
| 2 | x1 | r04 | 1.781 |
| 2 | x2 | r04 | 0.4723 |
| 2 | x3 | r04 | 0.8519 |
| 2 | x4 | r04 | 1.131 |
| 2 | x5 | r04 | 1.343 |
| -1 | x6 | r04 | 1.051 |
| -1 | x7 | r04 | 0.7797 |
| -1 | x8 | r04 | −0.9918 |
| -1 | x9 | r04 | 0.0180 |
| -1 | x10 | r04 | 1.769 |
| -1 | x11 | r04 | −0.1224 |
| -1 | x12 | r04 | 0.1363 |
| -1 | x1 | r05 | 1.355 |
| -1 | x2 | r05 | −0.0224 |
| -1 | x3 | r05 | 0.4606 |
| -1 | x4 | r05 | 0.7913 |
| -1 | x5 | r05 | 1.000 |
| -1 | x6 | r05 | −1.513 |
| -1 | x7 | r05 | −1.417 |
| -1 | x8 | r05 | −1.134 |
| -1 | x9 | r05 | 0.6560 |
| -1 | x10 | r05 | 2.149 |
| -1 | x11 | r05 | 0.8723 |
| -1 | x12 | r05 | −0.1323 |
First 60 of 720 rows.
Biclusters
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 10 | 4 | x7, x8, x9, x10 | 0.0027 | −0.3418 |
| 2 | 8 | 5 | x1, x2, x3, x4, x5 | 0.0112 | 0.0863 |
| 3 | 4 | 4 | x4, x6, x9, x11 | 0.0138 | 0.1289 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12")
ROW_ID <- "id" # row labels for the heatmap
SEED <- 42
ALGORITHM <- "cheng_church"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", col_select = unique(c(FEATURES, ROW_ID))))
n_input <- nrow(df)
cs_check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, FEATURES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 4, "Biclustering")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
dimnames(X) <- NULL
n <- nrow(X)
p <- ncol(X)
if (all(apply(X, 2, function(v) max(v) - min(v)) == 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
out <- cs_ml_out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-r")
rng <- cs_rng(SEED)
delta <- NULL
iterations <- NULL
need_nonnegative <- function(strict) {
bad <- if (strict) X <= 0 else X < 0
for (j in seq_along(FEATURES)) {
if (any(bad[, j])) cs_error("CS_E_INVALID_VALUES", column = FEATURES[j], requirement = if (strict) "positive" else "zero or more", count = sum(bad[, j]))
}
if (any(rowSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Row totals", requirement = "positive", count = sum(rowSums(X) <= 0))
if (any(colSums(X) <= 0)) cs_error("CS_E_INVALID_VALUES", column = "Column totals", requirement = "positive", count = sum(colSums(X) <= 0))
}
# %% Biclusters
if (ALGORITHM == "cheng_church") {
A <- X
if ("standard" == "standard") {
flat <- apply(A, 2, function(v) max(v) - min(v)) == 0
sd0 <- apply(A, 2, function(v) sqrt(mean((v - mean(v))^2)))
sd0[flat] <- 1
A <- sweep(sweep(A, 2, colMeans(A)), 2, sd0, "/")
A[, flat] <- 0 # constant columns exactly 0 in both engines
}
h_full <- cs_ml_bicluster_msr(A, rep(TRUE, n), rep(TRUE, p))
if (h_full <= 0) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
delta <- as.numeric(0.02) * h_full
found <- cs_ml_bicluster_cheng_church(A, 3, delta, as.numeric(1.2), rng)
biclusters <- found
if (!length(biclusters)) warnings <- c(warnings, "No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
} else if (ALGORITHM == "cocluster") {
need_nonnegative(FALSE)
K <- 3
n_sv <- if (K > 1) 1 + ceiling(log2(K)) else 1
if (K < 2 || n_sv > min(n, p) || K > n) {
cs_error("CS_E_INVALID_OPTION", option = "Biclusters", allowed = sprintf("between 2 and %d for this table", as.integer(min(n, 2^(min(n, p) - 1)))), value = K)
}
A <- X
co <- cs_ml_bicluster_cocluster(A, K, rng, 10)
biclusters <- lapply(seq_len(K) - 1L, function(b) list(I = co$rows == b, J = co$cols == b))
} else {
METHOD <- "bistochastic"
need_nonnegative(METHOD == "log")
NR <- 3
NC <- 3
NCOMP <- 6
NBEST <- 3
if (NCOMP > min(n, p)) cs_error("CS_E_INVALID_OPTION", option = "Singular vectors", allowed = sprintf("at most %d for this table", min(n, p)), value = NCOMP)
usable <- NCOMP - (if (METHOD == "log") 0 else 1)
if (NBEST > usable) cs_error("CS_E_INVALID_OPTION", option = "Vectors kept", allowed = sprintf("at most %d with %d singular vectors", usable, NCOMP), value = NBEST)
if (NR > n || NC > p) {
cs_error("CS_E_INVALID_OPTION", option = if (NR > n) "Row groups" else "Column groups", allowed = sprintf("at most %d", if (NR > n) n else p), value = if (NR > n) NR else NC)
}
A <- X
ch <- cs_ml_bicluster_checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
iterations <- ch$iterations
biclusters <- list()
for (r in seq_len(NR) - 1L) for (cc in seq_len(NC) - 1L) biclusters[[length(biclusters) + 1L]] <- list(I = ch$rows == r, J = ch$cols == cc)
}
# %% Summaries
k <- length(biclusters)
summ <- cs_ml_bicluster_summary(A, biclusters)
values <- list(n = n, p = p, k = k)
values["delta"] <- list(delta)
values["iterations"] <- list(iterations)
values$membership_check <- cs_ml_bicluster_checksum(biclusters)
covered_rows <- rep(FALSE, n)
covered_cells <- matrix(FALSE, n, p)
for (b in biclusters) {
covered_rows <- covered_rows | b$I
covered_cells[b$I, b$J] <- TRUE
}
values$rows_covered <- mean(covered_rows)
values$cells_covered <- mean(covered_cells)
msrs <- vapply(summ, function(s) s$msr, numeric(1))
msrs <- msrs[!is.nan(msrs)]
values["msr_mean"] <- list(if (length(msrs)) mean(msrs) else NULL)
for (b in seq_along(summ)) {
values[[sprintf("n_rows[%d]", b)]] <- summ[[b]]$n_rows
values[[sprintf("n_cols[%d]", b)]] <- summ[[b]]$n_cols
values[[sprintf("msr[%d]", b)]] <- summ[[b]]$msr
values[[sprintf("mean[%d]", b)]] <- summ[[b]]$mean
}
tables <- list(list(
key = "biclusters", title = "Biclusters",
columns = list(
list(key = "bicluster", label = "Bicluster", type = "integer"),
list(key = "rows", label = "Rows", type = "integer"),
list(key = "cols", label = "Columns", type = "integer"),
list(key = "columns", label = "Which columns", type = "string"),
list(key = "msr", label = "Mean squared residue", type = "number"),
list(key = "mean", label = "Mean value", type = "number")
),
rows = lapply(seq_along(biclusters), function(b) {
J <- biclusters[[b]]$J
nm <- FEATURES[which(J)]
list(bicluster = b, rows = summ[[b]]$n_rows, cols = summ[[b]]$n_cols,
columns = paste0(paste(utils::head(nm, 12), collapse = ", "), if (sum(J) > 12) " …" else ""),
msr = summ[[b]]$msr, mean = summ[[b]]$mean)
})
))
# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first <- rep(-1L, n)
flags <- list()
for (b in seq_along(biclusters)) {
I <- biclusters[[b]]$I
first[first == -1L & I] <- b
flags[[sprintf("in_%d", b)]] <- I
}
path <- do.call(cs_ml_write_labels, c(list(out, rows, first), flags))
bpath <- file.path(out, "biclusters.json")
bj <- list(k = k,
rows = lapply(biclusters, function(b) I(as.integer(rows[which(b$I)]))),
cols = lapply(biclusters, function(b) I(FEATURES[which(b$J)])))
writeLines(as.character(jsonlite::toJSON(bj, auto_unbox = TRUE)), bpath, useBytes = TRUE)
# %% Heatmap
charts <- list()
if (p <= 120 && k > 0) {
show <- if (n <= 400) seq_len(n) else which(covered_rows)[cs_ml_even_sample(sum(covered_rows), 400) + 1L]
if (!is.null(ROW_ID)) {
names <- cs_ml_label_text(df[[ROW_ID]][rows + 1L])
names[is.na(names)] <- ""
if (length(unique(names)) < n) names <- sprintf("%s #%d", names, seq_len(n))
} else {
names <- sprintf("row %d", rows + 1L)
}
cell_b <- matrix(-1L, n, p)
for (b in seq_along(biclusters)) {
I <- biclusters[[b]]$I
J <- biclusters[[b]]$J
blk <- cell_b[I, J, drop = FALSE]
blk[blk == -1L] <- b
cell_b[I, J] <- blk
}
rr <- rep(show, each = p)
jj <- rep(seq_len(p), times = length(show))
vlabel <- if (ALGORITHM == "cheng_church" && "standard" == "standard") "Value (standardized)" else "Value"
roles <- list(
row = cs_col("Row", names[rr], "categorical", levels = names[show]),
column = cs_col("Column", FEATURES[jj], "categorical", levels = FEATURES),
value = cs_col(vlabel, A[cbind(rr, jj)], "numeric")
)
if (k <= 29) roles$bicluster <- cs_col("Bicluster", as.character(cell_b[cbind(rr, jj)]), "categorical", levels = c(as.character(seq_len(k)), "-1"))
charts[[1]] <- cs_chart("heatmap", "bicluster-heatmap", "Biclusters in the table", roles,
note = if (length(show) == n) NULL else sprintf("%s of %s rows shown (rows in a bicluster, evenly sampled).", format(length(show), big.mark = ","), format(n, big.mark = ",")))
}
# %% Result
cs_publish(list(
title = "Biclustering (rows × columns)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = paste0(sprintf("%d bicluster%s in %s rows × %d columns covering %.0f%% of the rows", k, if (k != 1) "s" else "", format(n, big.mark = ","), p, values$rows_covered * 100),
if (!is.null(values$msr_mean)) sprintf("; mean squared residue %s.", format(signif(values$msr_mean, 3))) else "."),
statistics = list(list(key = "k", label = "Biclusters", value = k, format = "integer"),
list(key = "rows_covered", label = "Rows covered", value = values$rows_covered, format = "percent"),
list(key = "msr_mean", label = "Mean squared residue", value = values$msr_mean)),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
artifacts = list(list(key = "labels", path = path, format = "parquet"), list(key = "biclusters", path = bpath, format = "json")),
model = list(kind = "bicluster", features = I(FEATURES), params = list(
algorithm = "cheng_church",
k = 3,
delta_share = 0.02,
alpha = 1.2,
scale = "standard",
n_row_clusters = 3,
n_col_clusters = 3,
normalize = "bistochastic",
n_components = 6,
n_best = 3,
n_init = 10
))
))
3 biclusters in 60 rows × 12 columns covering 37% of the rows; mean squared residue 0.00923.
- Biclusters
- 3
- Rows covered
- 36.7%
- Mean squared residue
- 0.0092
To keep this page light, the plots are shown once, under the R tab.
Biclusters
| Bicluster | Rows | Columns | Which columns | Mean squared residue | Mean value |
|---|---|---|---|---|---|
| 1 | 10 | 4 | x7, x8, x9, x10 | 0.0027 | −0.3418 |
| 2 | 8 | 5 | x1, x2, x3, x4, x5 | 0.0112 | 0.0863 |
| 3 | 4 | 4 | x4, x6, x9, x11 | 0.0138 | 0.1289 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Biclustering (rows × columns)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.bicluster 1.0.0 · spec 31b304c79ce1b41c
# Dataset: clu4_bicluster (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import cluster_bicluster as cb
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
FEATURES = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12"]
ROW_ID = "id" # row labels for the heatmap
SEED = 42
ALGORITHM = "cheng_church"
df = pd.read_parquet("tests/parity/fixtures/clu4_bicluster.parquet", columns=list(dict.fromkeys(FEATURES + ([ROW_ID] if ROW_ID else []))))
n_input = len(df)
cs.check_finite_columns(df, FEATURES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, FEATURES)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 4, "Biclustering")
X = csembed.numeric_matrix(df, FEATURES, rows)
n, p = X.shape
if np.all(np.ptp(X, axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
out = csml.out_dir("target/academy-parity/run-85263/discover.bicluster/planted_cheng_church/out-python")
rng = Rng(SEED)
delta = None
iterations = None
def need_nonnegative(strict: bool) -> None:
bad = (X <= 0) if strict else (X < 0)
for j, f in enumerate(FEATURES):
if np.any(bad[:, j]):
cs.cs_error("CS_E_INVALID_VALUES", column=f, requirement="positive" if strict else "zero or more", count=int(np.sum(bad[:, j])))
if np.any(X.sum(axis=1) <= 0):
cs.cs_error("CS_E_INVALID_VALUES", column="Row totals", requirement="positive", count=int(np.sum(X.sum(axis=1) <= 0)))
if np.any(X.sum(axis=0) <= 0):
cs.cs_error("CS_E_INVALID_VALUES", column="Column totals", requirement="positive", count=int(np.sum(X.sum(axis=0) <= 0)))
# %% Biclusters
if ALGORITHM == "cheng_church":
A = X.copy()
if "standard" == "standard":
flat = np.ptp(A, axis=0) == 0
sd = A.std(axis=0, ddof=0)
sd[flat] = 1.0
A = (A - A.mean(axis=0)) / sd
A[:, flat] = 0.0 # constant columns exactly 0 in both engines
h_full = cb.msr(A, np.ones(n, dtype=bool), np.ones(p, dtype=bool))
if h_full <= 0:
cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
delta = float(0.02) * h_full
biclusters = cb.cheng_church(A, 3, delta, float(1.2), rng)
if not biclusters:
warnings.append("No block came below the residue threshold with at least two rows and two columns; raise the threshold.")
elif ALGORITHM == "cocluster":
need_nonnegative(strict=False)
K = 3
n_sv = 1 + int(np.ceil(np.log2(K))) if K > 1 else 1
if K < 2 or n_sv > min(n, p) or K > n:
cs.cs_error("CS_E_INVALID_OPTION", option="Biclusters", allowed=f"between 2 and {min(n, 2 ** (min(n, p) - 1))} for this table", value=K)
A = X
rl, cl = cb.cocluster(A, K, rng, 10)
biclusters = [(rl == b, cl == b) for b in range(K)]
else:
METHOD = "bistochastic"
need_nonnegative(strict=(METHOD == "log"))
NR, NC = 3, 3
NCOMP, NBEST = 6, 3
if NCOMP > min(n, p):
cs.cs_error("CS_E_INVALID_OPTION", option="Singular vectors", allowed=f"at most {min(n, p)} for this table", value=NCOMP)
usable = NCOMP - (0 if METHOD == "log" else 1)
if NBEST > usable:
cs.cs_error("CS_E_INVALID_OPTION", option="Vectors kept", allowed=f"at most {usable} with {NCOMP} singular vectors", value=NBEST)
if NR > n or NC > p:
cs.cs_error("CS_E_INVALID_OPTION", option="Row groups" if NR > n else "Column groups", allowed=f"at most {n if NR > n else p}", value=NR if NR > n else NC)
A = X
rl, cl, iterations = cb.checkerboard(A, NR, NC, METHOD, NCOMP, NBEST, rng, 10)
biclusters = [(rl == r, cl == c) for r in range(NR) for c in range(NC)]
# %% Summaries
k = len(biclusters)
summ = cb.summarize(A, biclusters)
values = {
"n": n, "p": p, "k": k, "delta": delta, "iterations": iterations,
"membership_check": cb.membership_checksum(biclusters, n, p),
}
covered_rows = np.zeros(n, dtype=bool)
covered_cells = np.zeros((n, p), dtype=bool)
for I, J in biclusters:
covered_rows |= I
covered_cells[np.ix_(I, J)] = True
values["rows_covered"] = float(np.mean(covered_rows))
values["cells_covered"] = float(np.mean(covered_cells))
msrs = [s["msr"] for s in summ if s["msr"] == s["msr"]]
values["msr_mean"] = float(np.mean(msrs)) if msrs else None
for b, s in enumerate(summ, start=1):
values[f"n_rows[{b}]"] = s["n_rows"]
values[f"n_cols[{b}]"] = s["n_cols"]
values[f"msr[{b}]"] = s["msr"]
values[f"mean[{b}]"] = s["mean"]
tables = [{
"key": "biclusters",
"title": "Biclusters",
"columns": [
{"key": "bicluster", "label": "Bicluster", "type": "integer"},
{"key": "rows", "label": "Rows", "type": "integer"},
{"key": "cols", "label": "Columns", "type": "integer"},
{"key": "columns", "label": "Which columns", "type": "string"},
{"key": "msr", "label": "Mean squared residue", "type": "number"},
{"key": "mean", "label": "Mean value", "type": "number"},
],
"rows": [
{"bicluster": b, "rows": s["n_rows"], "cols": s["n_cols"],
"columns": ", ".join([FEATURES[j] for j in np.flatnonzero(J)][:12]) + (" …" if int(J.sum()) > 12 else ""),
"msr": s["msr"], "mean": s["mean"]}
for b, ((I, J), s) in enumerate(zip(biclusters, summ), start=1)
],
}]
# %% Artifacts: labels.parquet (row, first bicluster, one flag per bicluster) and biclusters.json
first = np.full(n, -1, dtype=np.int64)
flags = {}
for b, (I, J) in enumerate(biclusters, start=1):
first[(first == -1) & I] = b
flags[f"in_{b}"] = I.copy()
path = csc.write_labels(out, rows, first, **flags)
bpath = os.path.join(out, "biclusters.json")
with open(bpath, "w", encoding="utf-8") as fh:
json.dump({"k": k, "rows": [[int(rows[i]) for i in np.flatnonzero(I)] for I, _ in biclusters],
"cols": [[FEATURES[j] for j in np.flatnonzero(J)] for _, J in biclusters]}, fh)
# %% Heatmap
charts = []
if p <= 120 and k > 0:
show = np.arange(n) if n <= 400 else np.flatnonzero(covered_rows)[csc.even_sample(int(covered_rows.sum()), 400)]
if ROW_ID:
names = cc.label_text(df[ROW_ID].iloc[rows].tolist())
names = np.array(["" if v is None else v for v in names], dtype=object)
if len(set(names.tolist())) < n:
names = np.array([f"{v} #{i + 1}" for i, v in enumerate(names)], dtype=object)
else:
names = np.array([f"row {int(r) + 1}" for r in rows], dtype=object)
cell_b = np.full((n, p), -1, dtype=np.int64)
for b, (I, J) in enumerate(biclusters, start=1):
sub = np.ix_(I, J)
blk = cell_b[sub]
blk[blk == -1] = b
cell_b[sub] = blk
rr = [int(i) for i in show for _ in range(p)]
jj = [j for _ in show for j in range(p)]
charts.append(cs.chart(
"heatmap", "bicluster-heatmap", "Biclusters in the table",
{
"row": cs.col("Row", [names[i] for i in rr], "categorical", levels=[names[i] for i in show]),
"column": cs.col("Column", [FEATURES[j] for j in jj], "categorical", levels=FEATURES),
"value": cs.col("Value (standardized)" if ALGORITHM == "cheng_church" and "standard" == "standard" else "Value",
[float(A[i, j]) for i, j in zip(rr, jj)], "numeric"),
"bicluster": cs.col("Bicluster", [str(cell_b[i, j]) for i, j in zip(rr, jj)], "categorical",
levels=[str(b) for b in range(1, k + 1)] + ["-1"]) if k <= 29 else None,
},
note=None if len(show) == n else f"{len(show):,} of {n:,} rows shown (rows in a bicluster, evenly sampled).",
))
# %% Result
cs.publish({
"title": "Biclustering (rows × columns)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": (f"{k} bicluster{'s' if k != 1 else ''} in {n:,} rows × {p} columns covering {values['rows_covered'] * 100:.0f}% of the rows"
+ (f"; mean squared residue {values['msr_mean']:.3g}." if values["msr_mean"] is not None else ".")),
"statistics": [
{"key": "k", "label": "Biclusters", "value": k, "format": "integer"},
{"key": "rows_covered", "label": "Rows covered", "value": values["rows_covered"], "format": "percent"},
{"key": "msr_mean", "label": "Mean squared residue", "value": values["msr_mean"]},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": path, "format": "parquet"}, {"key": "biclusters", "path": bpath, "format": "json"}],
"model": {"kind": "bicluster", "features": FEATURES, "params": {
"algorithm": "cheng_church",
"k": 3,
"delta_share": 0.02,
"alpha": 1.2,
"scale": "standard",
"n_row_clusters": 3,
"n_col_clusters": 3,
"normalize": "bistochastic",
"n_components": 6,
"n_best": 3,
"n_init": 10,
}},
})
The found blocks have an average residue of 0.00923. A tiny block has a low residue almost by default, so report area and overlap too.
Co-clusters and checkerboards
ReadSpectral co-clusteringSpectral co-clusteringPuts every row and every column in one of k blocks using singular vectors of the scaled table; needs non-negative values. scales a nonnegative matrix by its row and column sums, , and clusters rows and columns together from its singular vectors: each row and each column joins exactly one of blocks on the diagonal.
Spectral biclusteringCheckerboard biclusteringRow groups × column groups, each pair with its own level, found after row and column effects are scaled away. assumes a checkerboard: row groups times column groups, every cell with its own level. Normalization decides additive versus multiplicative structure, and zeros make the log version awkward.
Judge both sides of the result, rows and columns, and compare with plain row clustering to show the extra structure is worth it.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Stochastic blockmodel (UCL034) | Runs in CodeSplash (Experimental): Stochastic blockmodel on an edge list |
| Degree-corrected SBM (UCL035) | Runs in CodeSplash (Experimental): Stochastic blockmodel, Degree-corrected |
| Cheng–Church (UCL036) | Runs in CodeSplash: Biclustering (rows × columns), Cheng–Church |
| Spectral co-clustering (UCL037) | Runs in CodeSplash: Biclustering (rows × columns), Spectral co-clustering |
| Spectral biclustering (UCL038) | Runs in CodeSplash: Biclustering (rows × columns), Spectral biclustering (checkerboard) |
Check your understanding
CheckpointCheck yourself
A blockmodel fits a network with two blocks: one links to everyone, the other links only to the first. What has it found?
Show the answer
Answer: b
Blocks group nodes with similar linking patterns. Communities are one special case, where links are denser inside blocks than between them.
Check yourself
How should you choose the number of blocks?
Show the answer
Answer: b
More blocks always fit better. Penalties and held-out prediction weigh fit against complexity.
Check yourself
What does degree correction add to a blockmodel?
Show the answer
Answer: a
absorbs differences in how much nodes link. The block parameters then describe the pattern between groups.
Check yourself
When can degree correction mislead?
Show the answer
Answer: b
Compare it with the plain model by a penalty or held-out edges, and check the predicted degree distribution against the real one.
Check yourself
A Cheng–Church bicluster has a residue near zero. What does it mean?
Show the answer
Answer: b
Mean squared residue measures additive coherence. Rows can differ by a constant and still score zero.
Check yourself
Why isn't the lowest residue the best bicluster?
Show the answer
Answer: a
Report residue with the block's area and overlap, and test on held-out data before reading meaning into it.
Check yourself
What does spectral co-clustering assume about rows and columns?
Show the answer
Answer: b
It's a one-to-one pairing of row groups and column groups along the diagonal. Overlapping biclusters need a method like Cheng–Church.
Check yourself
Your matrix has negative values. What should you do before spectral co-clustering?
Show the answer
Answer: b
The row and column sum scaling assumes nonnegative entries, like counts. Shifting everything by a constant changes the structure the method sees.
Check yourself
Spectral biclustering finds three row groups and two column groups. How many blocks does it describe?
Show the answer
Answer: c
A checkerboard crosses row groups with column groups, and each cell has its own level.
Check yourself
How do you show a checkerboard is worth more than plain row clustering?
Show the answer
Answer: b
Reordered heatmaps flatter any method. Show what the column groups add on data the fit didn't see.
Do it on your own data
In the appLoad an edge list and open Stochastic blockmodel under Find segments; compare Degree-corrected with the plain model. For a table, open Biclustering (rows × columns) and pick Cheng–Church for overlapping coherent blocks or a spectral algorithm for a full partition.
Concepts in this lesson