Skip to content

CDiscover · discover.sbm

Stochastic blockmodel

Which nodes connect to the rest of the network in the same way, and how likely is a link between each pair of groups?

Fits a stochastic blockmodel: every node belongs to one of a few blocks, and the chance of a link depends only on the two nodes' blocks. Blocks can be communities (linked inside), a core and its periphery, or two sides that link only across (as buyers and sellers do). The degree-corrected model lets well-connected nodes have more links without needing a block of their own. It is fitted by variational EM from several starts; ICL (or BIC) picks the number of blocks. You get the block of each node with its certainty, the matrix of link rates between blocks and the network reordered by block. Starts come from the shared random stream, so Python and R find the same blocks.

Experimental Python and R agree to 6 decimals Seeded Also called stochastic block model, SBM, degree-corrected SBM…

A real result

Example “Karate dc”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Karate dcgraph_karate · source: member_a · target: member_b
  • Karate iclgraph_karate · source: member_a · target: member_b
  • Blocks bernoulligraph_blocks_edges · source: from · target: to
  • Coreper bicgrf2_coreper_edges · source: a · target: b
  • Bipartite dc countsgrf2_market_edges · source: buyer · target: seller · weight: orders
  • Degenerate n1graph_karate · source: member_a · target: member_b
  • Degenerate all nagraph_karate · source: member_a · target: member_b

In the guides

Where it sits in the decision guides

  • Structure: independent, hierarchical / grouped, temporal / spatial, networked · DS & ML Decision Guide · Key data characteristics — what influences method choice
  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

From (source)categorical / numeric · 1 column
One end of each edge: a person, page or station id.
To (target)categorical / numeric · 1 column
The other end of each edge.
Edge countnumeric · 0–1 column
Optional number of links between the two nodes (zero or more), read by the degree-corrected model. Repeated edges add up; without it every edge counts 1.

Choices you make

model

Modeldefault bernoulli

The plain model reads whether two nodes are linked; the degree-corrected model also lets nodes differ in how many links they have.

  • Stochastic blockmodel(default) — Each pair of nodes is linked with a probability set by their two blocks (Holland, Laskey & Leinhardt 1983). Hubs tend to get a block of their own.
  • Degree-corrected — Link counts follow a Poisson law scaled by both nodes' degrees, so blocks group nodes by whom they link to rather than how many links they have (Karrer & Newman 2011).
Blocksdefault —

A fixed number of blocks, or let the criterion choose between 1 and the largest number below.

Largest number of blocksdefault 6

When the criterion chooses: every number of blocks from 1 to this is fitted.

Criteriondefault icl

How the number of blocks is chosen.

  • ICL(default) — Integrated completed likelihood: favors blocks that are clearly separated (Biernacki et al. 2000; Daudin et al. 2008). The usual choice.
  • BIC — The variational lower bound minus the same penalty: tends to allow more, overlapping blocks.

Advanced

Startsdefault 5

Each fit starts this many times from k-means on the rows of the adjacency matrix (k-means++ seeds); the start with the best lower bound is kept.

options

Node tabledefault —

Optional table with one row per node: its label column is compared with the blocks (adjusted Rand index, NMI).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • An undirected network

    Edge directions are set aside and every pair of nodes is linked or not (the plain model) or linked a number of times (degree-corrected); self-loops are left out.

  • A local optimum

    Variational EM climbs to the nearest optimum; several starts make a poor one less likely, and the lower bound of each start is compared.

  • Blocks are roles

    Nodes share a block when they link alike, not necessarily to each other: read the block matrix before calling blocks communities.

What it reports

n_nodes
A network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks.
n_edges
A network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks.
density
A network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks.
model_label
A network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks.
blocks
A network model where each node sits in one block and the chance of a link depends only on the two nodes' blocks.
criterion_label
Each number of blocks is fitted and scored by ICL or BIC (fit minus a penalty for parameters); the highest score wins.
icl
Each number of blocks is fitted and scored by ICL or BIC (fit minus a penalty for parameters); the highest score wins.
bic
Each number of blocks is fitted and scored by ICL or BIC (fit minus a penalty for parameters); the highest score wins.
loglik
Alternates soft block memberships and link rates to raise a lower bound on the likelihood; each start climbs to a local optimum.
elbo
Alternates soft block memberships and link rates to raise a lower bound on the likelihood; each start climbs to a local optimum.
converged
Alternates soft block memberships and link rates to raise a lower bound on the likelihood; each start climbs to a local optimum.
certainty
Each node's largest block probability after the fit; the mean is near 1 when blocks are clearly separated.

Per group, level or term: n_labeled, ari, ami, nmi, size[<block>], share[<block>], rate[<block>,<block>], edges[<block>,<block>], icl[<Q>], bic[<Q>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, pandas, scipy, scikit-learn, codesplash; R uses nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same variational EM (codesplash.ml.sbm ↔ codesplashr R/ml_sbm.R) from the same k-means++ seeds (shared Wichmann–Hill stream) and Lloyd steps written out with ties to the lowest center; matrix products go through each engine's BLAS, which adds terms in a different order, so posteriors, rates and criteria agree to rounding (about 1e-12) rather than bit for bit, and blocks are renumbered by size in both.
  • The R packages sbm and blockmodels (GPL) start from other partitions and use other stopping rules, so their ICL and blocks can differ on hard networks (P2 against them).
Python

The exact script CodeSplash ran for example “Karate dc” · 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,
})
R

The exact script CodeSplash ran for example “Karate dc” · 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
))

Sources

  • Holland PW, Laskey KB, Leinhardt S (1983). Stochastic blockmodels: first steps. Social Networks 5:109–137.
  • Nowicki K, Snijders TAB (2001). Estimation and prediction for stochastic blockstructures. JASA 96:1077–1087.
  • Daudin J-J, Picard F, Robin S (2008). A mixture model for random graphs. Statistics and Computing 18:173–183.
  • Karrer B, Newman MEJ (2011). Stochastic blockmodels and community structure in networks. Phys Rev E 83:016107.
  • Biernacki C, Celeux G, Govaert G (2000). Assessing a mixture model for clustering with the integrated completed likelihood. IEEE TPAMI 22:719–725.
  • Latouche P, Birmelé E, Ambroise C (2012). Variational Bayesian inference and complexity control for stochastic block models. Statistical Modelling 12:93–115.

From the CodeSplash method registry · discover.sbm v1.0.0.