Skip to content

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.

Advanced ~14 min9 steps

What runs in CodeSplash

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

Read first

01

Generative models for structure

Read

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

02

The stochastic blockmodel

Read

A stochastic blockmodelStochastic blockmodelA network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks. gives each node a block ziz_i and links each pair independently with a probability that depends only on their blocks: Aij∣z,B∼Bernoulli(Bzizj)A_{ij}\mid z,B\sim\text{Bernoulli}(B_{z_i z_j}).

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.

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

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

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

Higher is better; ICL chose 2 blocks.

View data
BestCriterionBlocksCriterion
falseICL1−281.46
trueICL2−279.52
falseICL3−288.60
falseICL4−296.75
falseICL5−310.46
falseBIC1−281.46
trueBIC2−277.45
falseBIC3−284.83
falseBIC4−294.21
falseBIC5−308.17
Adjacency matrix by blockWhich nodes link to which, and do groups form blocks of dense ties?

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

View data
ColumnBlockNodeOrderRowEdge
51p01202
61p021101
111p032901
151p04501
321p052401
21p062711
31p073311
41p08111
51p09911
91p102811
111p113011
51p12021
62p13321
82p14721
92p153521
102p16421
212p17821
332p182521
352p192621
72p203131
82p213431
92p22631
292p231031
62p243641
81p252041
91p261441
71p271551
91p281951
261p292251
311p301251
91p313271
111p321871
242p332371
111p341681
111p3521101
151p3613111
281p3717111
30———111
16———121
17———121
18———121
19———121
22———121
23———121
19———131
23———131
15———141
16———141
18———141
19———141
20———141
22———141
23———141
18———151
19———151
20———151
22———151
21———161
22———161
20———171

First 60 of 98 rows.

Blocks in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromBlockNodeDegreeToxy
01p01550.0528−0.1113
01p0266−0.1108−0.2932
01p03911−0.0906−0.1818
01p04515−0.1865−0.2168
01p05432−0.0736−0.4174
11p0672−0.0193−0.2355
11p07330.0363−0.3021
11p0854−0.1432−0.2178
11p0945−0.1008−0.3271
11p1069−0.1547−0.3225
11p11211−0.0172−0.3266
21p1285−0.0373−0.1676
22p1366−0.03180.3014
22p14280.16590.3608
22p1579−0.03170.2386
22p16710−0.01500.0763
22p17421−0.12950.2473
22p182330.03320.3246
22p19535−0.11180.1693
32p20770.05630.2119
32p2188−0.05290.1429
32p2249−0.14470.0531
32p23729−0.00480.1757
42p24560.08990.2836
41p2578−0.1131−0.0468
41p26490.06750.0410
51p27470.1215−0.1360
51p2879−0.0003−0.0382
51p29626−0.0658−0.0729
51p30831−0.0631−0.0016
71p31690.0574−0.0253
71p32411−0.0036−0.1266
72p336240.04960.0970
81p347110.0035−0.0038
101p354110.1282−0.0237
111p36515−0.1602−0.0175
111p3702810.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

BlockNodesModel shareLink probability withinMean certaintyBest-connected nodes
12465.8%0.20390.9895p03, p12, p30
21334.2%0.37540.9538p21, p15, p16

Link probability between blocks

BlockBlock 1Block 2
Block 10.20390.0397
Block 20.03970.3754

Number of blocks

BlocksICLBICLower 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
))
Python

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

BlockNodesModel shareLink probability withinMean certaintyBest-connected nodes
12465.8%0.20390.9895p03, p12, p30
21334.2%0.37540.9538p21, p15, p16

Link probability between blocks

BlockBlock 1Block 2
Block 10.20390.0397
Block 20.03970.3754

Number of blocks

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

03

Hubs in a plain blockmodel

Predict

Predict 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?

By the two social groupsBy degree: hubs in one block, everyone else in the other
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.

04

Degree correction

Read

The 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 θi\theta_i: Aij∼Poisson(θiθj ωzizj)A_{ij}\sim\text{Poisson}(\theta_i\theta_j\,\omega_{z_iz_j}). Popular nodes link more without needing a block of their own; ω\omega describes the blocks.

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

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

Rate per degree pair (λ) between blocksWhat do the values of a square or rectangular result matrix look like at a glance?
View data
With blockBlockRate per degree pair (λ)
Block 1Block 10.0121
Block 2Block 10.0018
Block 1Block 20.0018
Block 2Block 20.0123
Adjacency matrix by blockWhich nodes link to which, and do groups form blocks of dense ties?

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

View data
ColumnBlockNodeOrderRowEdge
1202701
2212601
32102501
42111601
52123201
92132001
111142201
121152401
142161701
232171801
251182101
28219601
2922701
301201001
312211301
321221501
51231911
91243311
11125011
121261211
14127111
231282311
24129511
31232911
281303021
291313121
23132241
121331151
23242851
2725451
2626861
2727961
26181471
2719371
29———81
30———81
26———101
27———101
27———111
20———121
21———121
23———121
26———121
31———121
32———121
33———121
26———131
27———131
26———151
27———151
18———161
20———161
22———161
26———161
27———161
18———171
20———171
25———171
25———181
22———191

First 60 of 78 rows.

Blocks in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromBlockNodeDegreeToxy
020161−0.3181−0.2545
02192−0.2233−0.0757
021033−0.5988−0.5538
021114−0.7684−0.3116
021225−0.5555−0.3153
021359−0.0383−0.1016
01142110.65630.2455
01152120.5571−0.0469
0216214−0.5525−1
0217223−0.5518−0.1334
01182250.69510.1440
0219328−0.12180.0626
0221029−0.01840.0461
01202300.64960.0363
0221231−0.5239−0.0045
01222320.64640.3546
1123550.33250.4993
112439−0.05040.6329
11253110.11080.6623
11262120.62030.5661
11274140.12930.4353
11283230.14940.2290
11294240.50850.4495
123631−0.2882−0.1638
21304280.2164−0.0296
21316290.01650.2593
413212230.40040.1628
513317120.32490.2115
524323−0.4335−0.5876
525427−0.5362−0.7094
626426−0.4075−0.7379
627427−0.1466−0.2632
7185260.1237−0.0736
719227−0.00400.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

BlockNodesModel shareRate per degree pair (λ) withinMean certaintyBest-connected nodes
11851.6%0.01210.952733, 32, 31
21648.4%0.01230.97590, 2, 1

Rate per degree pair (λ) between blocks

BlockBlock 1Block 2
Block 10.01210.0018
Block 20.00180.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
))
Python

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

BlockNodesModel shareRate per degree pair (λ) withinMean certaintyBest-connected nodes
11851.6%0.01210.952733, 32, 31
21648.4%0.01230.97590, 2, 1

Rate per degree pair (λ) between blocks

BlockBlock 1Block 2
Block 10.01210.0018
Block 20.00180.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.

05

Cheng–Church: coherent submatrices

Read

Cheng–Church looks for a set of rows II and columns JJ that move in parallel. Its score is the mean squared residue

H(I,J)=1∣I∣∣J∣∑i∈I,j∈J(aij−aiJ−aIj+aIJ)2,H(I,J)=\frac{1}{|I||J|}\sum_{i\in I,j\in J}(a_{ij}-a_{iJ}-a_{Ij}+a_{IJ})^2,

what's left after removing row, column and overall means inside the block. It greedily deletes and adds rows and columns until HH is below a threshold δ\delta, masks the block and searches again.

Biclustering (rows × columns)Recorded · Python and R agreeRecorded 2026-11-21 · 21 values compared
R

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

Biclusters in the tableWhich subsets of rows share a pattern on a subset of columns?
View data
BiclusterColumnRowValue (standardized)
-1x1r011.166
-1x2r01−0.1202
-1x3r010.2679
-1x4r010.6042
-1x5r01−0.9826
-1x6r010.0277
-1x7r010.4645
-1x8r01−0.0677
-1x9r012.850
-1x10r010.2368
-1x11r01−0.4948
-1x12r01−0.1775
-1x1r020.0436
-1x2r02−1.401
-1x3r02−0.6471
-1x4r02−0.3771
-1x5r020.8307
-1x6r02−0.0856
-1x7r020.6873
-1x8r021.283
-1x9r020.9333
-1x10r02−1.728
-1x11r02−0.5257
-1x12r02−1.081
2x1r030.8580
2x2r03−0.5201
2x3r030.0291
2x4r030.3487
2x5r030.0055
-1x6r03−0.5167
-1x7r03−1.908
-1x8r03−0.4464
-1x9r031.701
-1x10r030.1065
-1x11r03−0.3729
-1x12r031.107
2x1r041.781
2x2r040.4723
2x3r040.8519
2x4r041.131
2x5r041.343
-1x6r041.051
-1x7r040.7797
-1x8r04−0.9918
-1x9r040.0180
-1x10r041.769
-1x11r04−0.1224
-1x12r040.1363
-1x1r051.355
-1x2r05−0.0224
-1x3r050.4606
-1x4r050.7913
-1x5r051.000
-1x6r05−1.513
-1x7r05−1.417
-1x8r05−1.134
-1x9r050.6560
-1x10r052.149
-1x11r050.8723
-1x12r05−0.1323

First 60 of 720 rows.

Biclusters

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.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
  ))
))
Python

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

BiclusterRowsColumnsWhich columnsMean squared residueMean value
1104x7, x8, x9, x100.0027−0.3418
285x1, x2, x3, x4, x50.01120.0863
344x4, x6, x9, x110.01380.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.

06

Co-clusters and checkerboards

Read

Spectral 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, A~=Dr−1/2ADc−1/2\tilde A=D_r^{-1/2}AD_c^{-1/2}, and clusters rows and columns together from its singular vectors: each row and each column joins exactly one of kk 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.

07

Where each idea stands in CodeSplash

Read
EntryIn 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)
08

Check your understanding

Checkpoint

Check 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

θi\theta_i absorbs differences in how much nodes link. The block parameters ω\omega 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.

09

Do it on your own data

In the app

Load 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