Skip to content

Clustering a graph: cuts, random walks, modularity and the map equation

Spectral clustering, Markov clustering, Chinese Whispers, Louvain, Leiden, Infomap and correlation clustering each define a good community differently. Which question each objective answers, and which checks keep them honest.

Advanced ~15 min11 steps

What runs in CodeSplash

You will be able to

  • Say which question each graph objective answers (cut, flow, label majority, modularity, code length, disagreements)
  • Explain the resolution setting and why a higher modularity doesn't prove real communities
  • Explain why Leiden was built to fix Louvain
  • Treat an eigengap as a clue, not a test

Read first

01

Same graph, different questions

Read

A graph has nodes and weighted edges: who emails whom, which products are bought together, or each row linked to its nearest neighbors. "Community" sounds like one idea, but each method optimizes its own:

MethodA good community is…
Spectral clusteringa set with few edges cut to the rest, relative to its size
Markov clustering, Infomapa place a random walk stays trapped
Chinese Whispersa set where each node shares its neighbors' majority label
Louvain, Leidendenser inside than the degrees alone predict (modularity)
Correlation clusteringa grouping that breaks the fewest "same" and "different" judgments

Pick the question first; the answers can differ on the same graph.

02

Spectral clustering: relax a cut

Read

From an affinity matrix WW and degrees Dii=∑jWijD_{ii}=\sum_j W_{ij}, spectral clustering takes the eigenvectors of the normalized Laplacian L=I−D−1/2WD−1/2L = I - D^{-1/2}WD^{-1/2} with the smallest eigenvalues and clusters their rows. Those eigenvectors are a relaxed solution to "cut few edges, keep the parts balanced".

Spectral clusteringRecorded · Python and R agreeRecorded 2026-11-25 · 30 values compared
R

Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.

Clusters
2
Mean silhouette
0.1181

Plots

ClustersWhich rows group together, and how well separated are the groups?
View data
Clusterxy
1−1.786−0.4692
2−0.21030.7162
10.62831.552
2−0.45210.6855
20.30240.2584
10.4395−1.697
20.4331−0.0558
20.4492−0.3593
2−0.4941−0.0709
2−0.4685−0.5394
2−0.05960.7036
2−0.7429−0.0588
1−1.062−1.517
1−0.31271.659
2−0.4611−0.2223
20.02350.5129
1−1.301−1.196
2−0.2439−0.6075
2−0.6338−0.1665
10.6791−1.553
2−0.6788−0.0244
10.56191.673
1−1.808−0.5330
2−0.54960.3045
2−0.2780−0.6040
2−0.25500.7943
1−1.273−1.445
10.0430−1.968
2−0.0387−0.6561
20.35720.2670
2−0.5418−0.2096
1−1.222−1.386
10.0128−1.606
1−1.266−1.102
11.488−0.5147
11.7220.3375
2−0.2139−0.5705
10.4204−1.897
2−0.4659−0.4211
1−1.8540.4413
11.7420.0514
1−0.2564−1.645
10.7345−1.555
10.34941.599
10.9373−1.515
2−0.50040.4092
2−0.4703−0.6429
2−0.3817−0.5890
1−1.078−1.501
20.40950.1630
2−0.5402−0.4220
11.534−1.208
10.81121.521
20.2235−0.5717
10.6529−1.479
10.9315−1.534
11.3060.9765
11.2711.018
11.4160.9223
10.4963−1.663

First 60 of 300 rows.

Eigenvalues of the normalized similarity matrixHow many clusters does the data support?

The largest gap after eigenvalue 8 suggests k = 8.

View data
Largest gapEigenvalue (rank)Eigenvalue
false11
false21
false30.9940
false40.9936
false50.9825
false60.9816
false70.9777
true80.9734
false90.9506
false100.9430
Silhouette widthsHow well does each row fit its cluster compared with the next-nearest cluster?
View data
ClusterSilhouette width
1−0.1058
1−0.1103
1−0.1161
1−0.1178
1−0.1204
1−0.1207
1−0.1213
1−0.1218
1−0.1242
1−0.1270
1−0.1278
1−0.1282
1−0.1297
1−0.1299
1−0.1308
1−0.1308
1−0.1315
1−0.1325
1−0.1332
1−0.1339
1−0.1346
1−0.1354
1−0.1362
1−0.1366
1−0.1381
1−0.1384
1−0.1399
1−0.1400
1−0.1419
1−0.1426
1−0.1438
1−0.1449
1−0.1451
1−0.1452
1−0.1456
1−0.1474
1−0.1475
1−0.1481
1−0.1493
1−0.1495
1−0.1510
1−0.1513
1−0.1518
1−0.1518
1−0.1538
1−0.1539
1−0.1543
1−0.1544
1−0.1546
1−0.1548
1−0.1556
1−0.1559
1−0.1562
1−0.1584
1−0.1586
1−0.1588
1−0.1602
1−0.1607
1−0.1607
1−0.1608

First 60 of 300 rows.

Clusters

ClusterSizeSharexy
118060.0%0.27470.0557
212040.0%−0.03340.0052
  • The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.
The exact R script · R R version 4.5.1 (2025-06-13)
# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 638b2a0c45f9d88a
# Dataset: clu2_rings (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("x", "y")
LABEL <- "ring"  # known groups (external validation only)
ROW_ID <- NULL  # row labels for charts
SEED <- 42
KINDS <- list(
  x = "numeric",
  y = "numeric"
)
LEVELS <- list(
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/clu2_rings.parquet", col_select = unique(c(FEATURES, LABEL, ROW_ID))))
n_input <- nrow(df)
prep <- cs_ml_cluster_prepare(df, FEATURES, KINDS, LEVELS, missing = "drop", scale = "standard")
X <- prep$X; rows <- prep$rows; names_ <- prep$names; frame <- prep$frame
warnings <- list()
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a feature was missing.", n_input - length(rows), n_input))
}
if (length(rows) < 3) stop("Clustering needs at least three rows with every feature present.")
truth <- if (!is.null(LABEL)) as.character(frame[[LABEL]]) else NULL
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.spectral/rings_knn/out-r")
values <- list(n_used = length(rows))
centers <- NULL
center_ids <- NULL
D <- NULL
extra <- list()
tables <- list()
charts <- list()
summary <- NULL

# %% Clustering
cs_check_finite_columns(frame, FEATURES[vapply(FEATURES, function(f) identical(KINDS[[f]], "numeric"), logical(1))])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K <- 2
ALGO <- "spectral"
AFFINITY <- "knn"
GAMMA <- NULL
n <- length(rows)
if (K >= n) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("Spectral clustering with k = %d", K), min = K + 1, n = n)
if (n > 3000) stop("Spectral clustering keeps an n × n similarity matrix; use it on at most 3,000 rows.")
if (ALGO == "kernel_kmeans" && AFFINITY == "knn") {
  cs_error("CS_E_INVALID_OPTION", option = "Similarity graph", allowed = "the Gaussian (RBF) kernel for kernel k-means", value = "k nearest neighbors")
}
if (!any(apply(X, 2, function(v) max(v) - min(v)) > 0)) cs_error("CS_E_CONSTANT", column = paste(FEATURES, collapse = ", "))
D2 <- cs_ml_sq_dists(X, X)
g <- if (!is.null(GAMMA)) as.numeric(GAMMA) else cs_ml_rbf_gamma(D2)
if (ALGO == "spectral") {
  nn <- min(10, n - 1)
  if (AFFINITY == "knn") values$n_neighbors <- nn else values$gamma <- g
  emb <- cs_ml_spectral_embed(cs_ml_affinity_matrix(D2, AFFINITY, g, nn), K)
  if (!is.null(emb$isolated)) cs_error("CS_E_UNDEFINED", what = "Spectral clustering", reason = sprintf("%d rows have no similar neighbor (lower the kernel width γ)", emb$isolated))
  ev <- emb$eigenvalues
  if (abs(ev[K] - ev[K + 1]) <= 1e-8 * max(1, abs(ev[K]))) {
    # tied eigenvalues at k: the k-dimensional embedding (and so the clusters) is not unique
    cs_error("CS_E_UNDEFINED", what = sprintf("Spectral clustering with k = %d", K), reason = sprintf("eigenvalues %d and %d of the similarity graph are tied, so the split into %d clusters is not unique; choose another k", K, K + 1, K))
  }
  km <- cs_ml_kmeans_fit(emb$Y, K, cs_rng(SEED), n_init = 10, max_iter = 300)
  raw <- km$labels
  values$embedding_inertia <- km$inertia
  m <- min(length(ev), max(10, K + 1))
  for (i in seq_len(m)) values[[sprintf("eigenvalue[%d]", i)]] <- ev[i]
  values$eigengap <- ev[K] - ev[K + 1]
  cand <- if (min(m, n - 1) > 2) 2:(min(m, n - 1) - 1) else integer(0)
  values$suggested_k <- if (length(cand)) {
    gaps <- vapply(cand, function(j) ev[j] - ev[j + 1], numeric(1))
    cand[which.max(gaps)]
  } else K
  values$n_components <- sum(ev > 1 - 1e-9)
  if (values$n_components > 1) warnings <- c(warnings, sprintf("The similarity graph falls into %d disconnected parts; each part needs at least one cluster.", values$n_components))
  xs <- seq_len(m)
  charts <- c(charts, list(cs_chart(
    "eigenvalues", "elbow-plot", "Eigenvalues of the normalized similarity matrix",
    list(k = cs_col("Eigenvalue (rank)", xs, "numeric"), score = cs_col("Eigenvalue", ev[seq_len(m)], "numeric"),
         chosen = cs_col("Largest gap", xs == values$suggested_k, "boolean")),
    note = sprintf("The largest gap after eigenvalue %d suggests k = %d.", values$suggested_k, values$suggested_k)
  )))
  summary <- sprintf("Spectral clustering with k = %d on a %s graph; the largest eigenvalue gap suggests k = %d.",
                     K, if (AFFINITY == "knn") "nearest-neighbor" else "Gaussian kernel", values$suggested_k)
} else {
  values$gamma <- g
  fit <- cs_ml_kernel_kmeans(exp(-g * D2), K, cs_rng(SEED), n_init = 10, max_iter = 300)
  raw <- fit$labels
  values$objective <- fit$objective
  values$iterations <- fit$iterations
  if (!fit$converged) warnings <- c(warnings, "Kernel k-means stopped at the iteration limit before the clusters settled.")
  if (length(unique(raw)) < K) warnings <- c(warnings, sprintf("%d cluster(s) ended with no rows.", K - length(unique(raw))))
  summary <- sprintf("Kernel k-means with k = %d (RBF, γ = %s): within-cluster kernel distance %s.", K,
                     formatC(g, digits = 3, format = "g"), formatC(values$objective, digits = 4, format = "g"))
}

# %% Canonical labels and validation
labels <- cs_ml_canonical(raw)
ids <- sort(unique(labels[labels != -1]))
k <- length(ids)
values$k <- k
values$n_noise <- sum(labels == -1)
if (!is.null(centers)) {
  cid <- if (is.null(center_ids)) seq_len(nrow(centers)) - 1L else center_ids
  raw_of <- vapply(ids, function(c) raw[which(labels == c)[1]], numeric(1))
  centers <- centers[match(raw_of, cid), , drop = FALSE]
  for (i in seq_along(ids)) for (j in seq_along(names_)) {
    values[[sprintf("center[%d,%s]", ids[i], names_[j])]] <- centers[i, j]
  }
}
sz <- cs_ml_cluster_sizes(labels)
for (c in names(sz)) values[[sprintf("size[%s]", c)]] <- sz[[c]]
check <- cs_ml_cluster_validation(X, labels, truth, D = D, cap = 3000, seed = SEED)
widths <- check$.widths
check$.widths <- NULL
values <- c(values, check)
profile_rows <- list()
for (c in ids) {
  member <- labels == c
  row <- list(cluster = c, size = sum(member), share = mean(member))
  for (f in FEATURES) {
    if (identical(KINDS[[f]], "numeric")) {
      m <- mean(suppressWarnings(as.numeric(frame[[f]]))[member], na.rm = TRUE)
      row[[f]] <- m
      values[[sprintf("mean[%d,%s]", c, f)]] <- m
    } else {
      v <- as.character(frame[[f]])[member]
      v <- v[!is.na(v)]
      top <- if (length(v)) sort(table(v), decreasing = TRUE) else NULL
      row[[f]] <- if (length(top)) sprintf("%s (%.0f%%)", names(top)[1], 100 * top[[1]] / sum(member)) else ""
    }
  }
  profile_rows[[length(profile_rows) + 1L]] <- row
}
tables <- c(list(list(
  key = "clusters", title = "Clusters",
  columns = c(list(list(key = "cluster", label = "Cluster", type = "integer"),
                   list(key = "size", label = "Size", type = "integer"),
                   list(key = "share", label = "Share", type = "percent")),
              lapply(FEATURES, function(f) list(key = f, label = f, type = if (identical(KINDS[[f]], "numeric")) "number" else "string"))),
  rows = profile_rows
)), tables)

# %% Labels file and charts
path <- do.call(cs_ml_write_labels, c(list(out, rows, labels), extra))
name_of <- function(c) as.character(c)  # noise stays "-1" (drawn gray, listed last)
pr <- cs_ml_project2(X, centers, names_)
show <- cs_ml_even_sample(length(rows))
xs <- pr$P[show + 1L, 1]; ys <- pr$P[show + 1L, 2]
cl <- name_of(labels[show + 1L])
cent <- rep(FALSE, length(show))
lab <- if (!is.null(ROW_ID)) as.character(frame[[ROW_ID]])[show + 1L] else NULL
if (!is.null(pr$C)) {
  xs <- c(xs, pr$C[, 1]); ys <- c(ys, pr$C[, 2])
  cl <- c(cl, name_of(ids)); cent <- c(cent, rep(TRUE, length(ids)))
  if (!is.null(lab)) lab <- c(lab, sprintf("center %d", ids))
}
level_names <- c(as.character(ids), if (values$n_noise > 0) "-1")
charts <- c(list(cs_chart(
  "clusters", "cluster-scatter", "Clusters",
  list(x = cs_col(pr$labels[1], xs, "numeric"), y = cs_col(pr$labels[2], ys, "numeric"),
       cluster = cs_col("Cluster", cl, "categorical", levels = level_names),
       centroid = if (!is.null(pr$C)) cs_col("Center", cent, "boolean"),
       label = if (!is.null(lab)) cs_col("Row", lab, "categorical")),
  note = if (length(show) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(show), big.mark = ","), format(length(rows), big.mark = ","))
)), charts)
if (!is.nan(values$silhouette)) {
  wl <- labels[widths$pick + 1L]
  o <- order(wl, -widths$width)
  charts[[length(charts) + 1L]] <- cs_chart(
    "silhouette", "silhouette-plot", "Silhouette widths",
    list(cluster = cs_col("Cluster", as.character(wl[o]), "categorical", levels = as.character(ids)),
         width = cs_col("Silhouette width", widths$width[o], "numeric")),
    note = if (length(widths$pick) == sum(labels != -1)) NULL else sprintf("%s rows sampled for the silhouette.", format(length(widths$pick), big.mark = ","))
  )
}

# %% Result
if (is.null(summary)) {
  summary <- sprintf("%d cluster%s in %s rows", k, if (k != 1) "s" else "", format(length(rows), big.mark = ","))
  if (values$n_noise > 0) summary <- paste0(summary, sprintf(" (%s noise points)", format(values$n_noise, big.mark = ",")))
  if (!is.nan(values$silhouette)) summary <- paste0(summary, sprintf("; mean silhouette %.2f", values$silhouette))
  summary <- paste0(summary, ".")
}
cs_publish(list(
  title = "Spectral clustering",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "k", label = "Clusters", value = k, format = "integer"),
                    list(key = "silhouette", label = "Mean silhouette", value = values$silhouette)),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = path, format = "parquet")),
  model = list(kind = "clusterer", features = I(names_), params = list(
    k = 2,
    algorithm = "spectral",
    affinity = "knn",
    gamma = NULL,
    n_neighbors = 10,
    n_init = 10,
    scale = "standard",
    missing = "drop"
  ))
))
Python

Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.

Clusters
2
Mean silhouette
0.1181

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

Clusters

ClusterSizeSharexy
118060.0%0.27470.0557
212040.0%−0.03340.0052
  • The similarity graph falls into 2 disconnected parts; each part needs at least one cluster.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Spectral clustering
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.spectral 1.0.0 · spec 638b2a0c45f9d88a
# Dataset: clu2_rings (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 ml as csml
from codesplash.ml import cluster as csc
from codesplash.stats.rng import Rng
from codesplash.ml import cluster_partitional as cpart

# %% Data
FEATURES = ["x", "y"]
LABEL = "ring"  # known groups (external validation only)
ROW_ID = None  # row labels for charts
SEED = 42
KINDS = {
    "x": "numeric",
    "y": "numeric",
}
LEVELS = {
}
df = pd.read_parquet("tests/parity/fixtures/clu2_rings.parquet", columns=list(dict.fromkeys(FEATURES + [c for c in (LABEL, ROW_ID) if c])))
n_input = len(df)
X, rows, names, frame = csc.prepare(df, FEATURES, KINDS, LEVELS, missing="drop", scale="standard")
warnings = []
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a feature was missing.")
if len(rows) < 3:
    raise ValueError("Clustering needs at least three rows with every feature present.")
truth = frame[LABEL].astype("object").to_numpy() if LABEL else None
out = csml.out_dir("target/academy-parity/run-8142/discover.spectral/rings_knn/out-python")
values = {"n_used": len(rows)}
centers = None
center_ids = None
D = None
extra = {}
tables = []
charts = []
summary = None

# %% Clustering
cs.check_finite_columns(frame, [f for f in FEATURES if KINDS[f] == "numeric"])  # ±Inf stops with CS_E_NOT_FINITE in both engines
K = 2
ALGO = "spectral"
AFFINITY = "knn"
GAMMA = None
n = len(rows)
if K >= n:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"Spectral clustering with k = {K}", min=K + 1, n=n)
if n > 3000:
    raise ValueError("Spectral clustering keeps an n × n similarity matrix; use it on at most 3,000 rows.")
if ALGO == "kernel_kmeans" and AFFINITY == "knn":
    cs.cs_error("CS_E_INVALID_OPTION", option="Similarity graph", allowed="the Gaussian (RBF) kernel for kernel k-means", value="k nearest neighbors")
if not np.any(np.ptp(X, axis=0) > 0):
    cs.cs_error("CS_E_CONSTANT", column=", ".join(FEATURES))
D2 = cpart.pairwise_sq(X)
g = float(GAMMA) if GAMMA is not None else cpart.rbf_gamma(D2)
if ALGO == "spectral":
    nn = min(10, n - 1)
    if AFFINITY == "knn":
        values["n_neighbors"] = nn
    else:
        values["gamma"] = g
    emb = cpart.spectral_embed(cpart.affinity_matrix(D2, AFFINITY, g, nn), K)
    if "isolated" in emb:
        cs.cs_error("CS_E_UNDEFINED", what="Spectral clustering", reason=f"{emb['isolated']} rows have no similar neighbor (lower the kernel width γ)")
    ev = emb["eigenvalues"]
    if abs(ev[K - 1] - ev[K]) <= 1e-8 * max(1.0, abs(ev[K - 1])):
        # tied eigenvalues at k: the k-dimensional embedding (and so the clusters) is not unique
        cs.cs_error("CS_E_UNDEFINED", what=f"Spectral clustering with k = {K}", reason=f"eigenvalues {K} and {K + 1} of the similarity graph are tied, so the split into {K} clusters is not unique; choose another k")
    lab, _, inertia = csc.kmeans_fit(emb["Y"], K, Rng(SEED), n_init=10, max_iter=300)
    raw = lab
    values["embedding_inertia"] = inertia
    m = min(len(ev), max(10, K + 1))
    for i in range(m):
        values[f"eigenvalue[{i + 1}]"] = float(ev[i])
    values["eigengap"] = float(ev[K - 1] - ev[K])
    cand = list(range(2, min(m, n - 1)))
    values["suggested_k"] = int(max(cand, key=lambda j: (ev[j - 1] - ev[j], -j))) if cand else K
    values["n_components"] = int(np.sum(ev > 1.0 - 1e-9))
    if values["n_components"] > 1:
        warnings.append(f"The similarity graph falls into {values['n_components']} disconnected parts; each part needs at least one cluster.")
    xs = list(range(1, m + 1))
    charts.append(cs.chart(
        "eigenvalues", "elbow-plot", "Eigenvalues of the normalized similarity matrix",
        {"k": cs.col("Eigenvalue (rank)", xs, "numeric"), "score": cs.col("Eigenvalue", [float(ev[i]) for i in range(m)], "numeric"),
         "chosen": cs.col("Largest gap", [x == values["suggested_k"] for x in xs], "boolean")},
        note=f"The largest gap after eigenvalue {values['suggested_k']} suggests k = {values['suggested_k']}.",
    ))
    summary = (
        f"Spectral clustering with k = {K} on a {'nearest-neighbor' if AFFINITY == 'knn' else 'Gaussian kernel'} graph; "
        f"the largest eigenvalue gap suggests k = {values['suggested_k']}."
    )
else:
    values["gamma"] = g
    fit = cpart.kernel_kmeans(np.exp(-g * D2), K, Rng(SEED), n_init=10, max_iter=300)
    raw = fit["labels"]
    values["objective"] = fit["objective"]
    values["iterations"] = fit["iterations"]
    if not fit["converged"]:
        warnings.append("Kernel k-means stopped at the iteration limit before the clusters settled.")
    if len(set(raw.tolist())) < K:
        warnings.append(f"{K - len(set(raw.tolist()))} cluster(s) ended with no rows.")
    summary = f"Kernel k-means with k = {K} (RBF, γ = {g:.3g}): within-cluster kernel distance {values['objective']:.4g}."

# %% Canonical labels and validation
labels = csc.canonical(raw)
ids = [int(c) for c in sorted(set(labels.tolist())) if c != -1]
k = len(ids)
values["k"] = k
values["n_noise"] = int(np.sum(labels == -1))
if centers is not None:
    # reorder centers to canonical ids: the raw id of each canonical cluster
    raw_of = {c: raw[np.flatnonzero(labels == c)[0]] for c in ids}
    pos = {int(r): i for i, r in enumerate(center_ids if center_ids is not None else range(len(centers)))}
    centers = np.array([centers[pos[int(raw_of[c])]] for c in ids])
    for c, row in zip(ids, centers):
        for name, v in zip(names, row):
            values[f"center[{c},{name}]"] = float(v)
for c, m in csc.sizes(labels).items():
    values[f"size[{c}]"] = m
check = csc.validation(X, labels, truth, D=D, cap=3000, seed=SEED)
widths, picked = check.pop("_widths")
values.update(check)
# per-cluster means of numeric features in their own units (interpretation)
profile_rows = []
for c in ids:
    member = labels == c
    row = {"cluster": c, "size": int(member.sum()), "share": float(member.mean())}
    for f in FEATURES:
        if KINDS[f] == "numeric":
            m = float(np.nanmean(pd.to_numeric(frame[f], errors="coerce").to_numpy(dtype=np.float64)[member]))
            row[f] = m
            values[f"mean[{c},{f}]"] = m
        else:
            top = pd.Series(frame[f].astype("object").to_numpy()[member]).dropna().astype(str).value_counts()
            row[f] = f"{top.index[0]} ({top.iloc[0] / member.sum():.0%})" if len(top) else ""
    profile_rows.append(row)
tables.insert(0, {
    "key": "clusters",
    "title": "Clusters",
    "columns": [
        {"key": "cluster", "label": "Cluster", "type": "integer"},
        {"key": "size", "label": "Size", "type": "integer"},
        {"key": "share", "label": "Share", "type": "percent"},
    ]
    + [{"key": f, "label": f, "type": "number" if KINDS[f] == "numeric" else "string"} for f in FEATURES],
    "rows": profile_rows,
})

# %% Labels file and charts
path = csc.write_labels(out, rows, labels, **extra)
name_of = lambda c: str(c)  # noqa: E731  — noise stays "-1" (drawn gray, listed last)
P, C, axes = csc.project2(X, centers, names)
show = csc.even_sample(len(rows))
point_labels = [str(v) for v in frame[ROW_ID].astype("object").to_numpy()[show]] if ROW_ID else None
xs, ys = list(P[show, 0]), list(P[show, 1])
cl = [name_of(c) for c in labels[show]]
cent = [False] * len(show)
lab = point_labels
if C is not None:
    xs += list(C[:, 0])
    ys += list(C[:, 1])
    cl += [name_of(c) for c in ids]
    cent += [True] * len(ids)
    lab = None if lab is None else lab + [f"center {c}" for c in ids]
level_names = [str(c) for c in ids] + (["-1"] if values["n_noise"] else [])
charts.insert(0, cs.chart(
    "clusters", "cluster-scatter", "Clusters",
    {
        "x": cs.col(axes[0], xs, "numeric"),
        "y": cs.col(axes[1], ys, "numeric"),
        "cluster": cs.col("Cluster", cl, "categorical", levels=level_names),
        "centroid": cs.col("Center", cent, "boolean") if C is not None else None,
        "label": cs.col("Row", lab, "categorical") if lab is not None else None,
    },
    note=None if len(show) == len(rows) else f"{len(show):,} of {len(rows):,} rows shown.",
))
if not np.isnan(values["silhouette"]):
    wl = labels[picked]
    order = np.lexsort((-widths, wl))
    charts.append(cs.chart(
        "silhouette", "silhouette-plot", "Silhouette widths",
        {"cluster": cs.col("Cluster", [str(c) for c in wl[order]], "categorical", levels=[str(c) for c in ids]),
         "width": cs.col("Silhouette width", list(widths[order]), "numeric")},
        note=None if len(picked) == int(np.sum(labels != -1)) else f"{len(picked):,} rows sampled for the silhouette.",
    ))

# %% Result
if summary is None:
    summary = f"{k} cluster{'s' if k != 1 else ''} in {len(rows):,} rows"
    if values["n_noise"]:
        summary += f" ({values['n_noise']:,} noise points)"
    if not np.isnan(values["silhouette"]):
        summary += f"; mean silhouette {values['silhouette']:.2f}"
    summary += "."
cs.publish({
    "title": "Spectral clustering",
    "engine": cs.engine_info("numpy", "scikit-learn", "numpy", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Clusters", "value": k, "format": "integer"},
        {"key": "silhouette", "label": "Mean silhouette", "value": values["silhouette"]},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": path, "format": "parquet"}],
    "model": {"kind": "clusterer", "features": names, "params": {
        "k": 2,
        "algorithm": "spectral",
        "affinity": "knn",
        "gamma": None,
        "n_neighbors": 10,
        "n_init": 10,
        "scale": "standard",
        "missing": "drop",
    }},
})

On two nested rings with a nearest-neighbor graph it recovers the rings exactly (adjusted Rand 1), yet the eigengap heuristic suggested 8 clusters. The eigengap is a clue, not a test, and how you build the graph drives the result.

03

Cut a neighbor graph

Explore

AExplorable · Spectral clustering: cut a neighbor graph

How can clustering follow curved shapes that k-means slices straight through?

Which recovers the planted groups better on this data: k-means on the points, or k-means on the graph's eigenvectors?

How sure?

Data

2
8
120
Simulating…

Commit your prediction above to see the result

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

Make your prediction to see the result.

Join each point to its nearest neighbors, then cluster the graph's smallest eigenvectors. Moons that k-means slices straight across come apart; too many neighbors bridge the gap and blur them.

04

Random walks: MCL and Chinese Whispers

Read

Markov clusteringMarkov clusteringAlternately spreads a random walk (expansion) and sharpens it (inflation); walks end trapped in dense groups, the clusters. turns the adjacency matrix (with self-loops) into a column-stochastic matrix PP and alternates expansion, P←PeP\leftarrow P^e (walk further), with inflation, raising entries to a power r>1r>1 and renormalizing (strong paths get stronger). Flow stays inside dense regions; inflation sets the granularity. On the karate club graph it found 2 communities.

Chinese WhispersChinese WhispersGraph clustering where each node, in random order, takes the label carrying most edge weight among its neighbors until labels settle. gives every node its own label, then visits nodes in random order and sets each to the weighted majority label of its neighbors, zi←arg⁡max⁡c∑j∈N(i)wij1(zj=c)z_i\leftarrow\arg\max_c\sum_{j\in N(i)} w_{ij}\mathbf 1(z_j=c). It's fast and needs no kk, but the visit order matters: compare repeated runs and report the unstable nodes.

05

Modularity: Louvain and Leiden

Read

ModularityModularityThe share of link weight inside communities minus the share expected if links fell at random given each node's degree. compares the edges inside communities with what degrees alone would predict: Q=12m∑ij[Aij−γkikj2m]1(zi=zj)Q=\frac{1}{2m}\sum_{ij}\big[A_{ij}-\gamma\frac{k_ik_j}{2m}\big]\mathbf 1(z_i=z_j). The resolution γ\gamma sets the scale: on a block graph, γ\gamma = 2.50 split it into 11 communities.

LouvainLouvain algorithmMoves each node to the neighboring community that raises modularity most, then merges communities into nodes and repeats. moves nodes greedily and merges communities into super-nodes; it can leave a community internally disconnected. LeidenLeiden algorithmLouvain with a refinement step that splits each community into well-connected parts before merging, so none falls apart. adds a refinement step that keeps every community in one piece. It can also use the constant Potts model, whose resolution is on a different numeric scale, so don't carry a γ\gamma across objectives.

06

A higher modularity

Predict
Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

Leiden found 4 communities among 34 nodes; 73% of the edge weight falls inside them (modularity 0.420).

Communities
4
Modularity
0.4198
Edge weight inside
73.1%

Plots

Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToxy
020161−0.3181−0.2545
02192−0.2233−0.0757
041033−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
0416214−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
1323550.33250.4993
132439−0.05040.6329
13253110.11080.6623
11262120.62030.5661
13274140.12930.4353
13283230.14940.2290
11294240.50850.4495
123631−0.2882−0.1638
21304280.2164−0.0296
23316290.01650.2593
413212230.40040.1628
513317120.32490.2115
544323−0.4335−0.5876
545427−0.5362−0.7094
646426−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.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowEdge
1202701
2212601
34103201
42112201
52122401
9213601
11114701
121151001
144161301
232171501
251181901
282193301
2922001
301201201
31221101
321222301
5323511
93243111
113251111
12126411
14327911
233281411
24129311
31232511
281301621
293312021
231321741
121331851
23442151
27452951
26463061
2727261
26182871
2719871
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.

Community sizesHow often does each category occur?
View data
Community
2
2
4
2
2
2
1
1
4
2
1
2
2
1
2
1
3
3
3
1
3
3
1
2
1
3
1
1
4
4
4
2
1
1

Communities

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11235.3%0.2500yes33, 32, 8
21132.4%0.2333yes0, 2, 1
3617.6%0.4167yes31, 23, 27
4514.7%0.2500yes5, 6, 10
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ab902ef908a98ec8
# 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_comm_*(): twin of codesplash.ml.communities

ALGO <- "leiden"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- FALSE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/leiden_karate/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()

# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
  cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
  warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L

# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
  gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
  values$resolution <- gamma
}

find <- function(setting) {
  rng <- cs_rng(SEED) # a fresh stream for every setting
  if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
  if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
  if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
  if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
  fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
  cs_ml_comm_infomap(fl, rng, TRIALS)
}

setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
  values$converged <- isTRUE(res$converged)
  if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
  values$codelength <- res$codelength
  values$codelength_one <- res$one_module
}

# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
  values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
  ok <- !is.na(truth)
  values$n_labeled <- sum(ok)
  if (sum(ok) >= 2) {
    values$ari <- cs_ml_ari(truth[ok], labels[ok])
    values$ami <- cs_ml_ami(truth[ok], labels[ok])
    values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
  }
}

# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
  grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
  srows <- list(); ks <- integer(0); qs <- numeric(0)
  for (i in seq_along(grid)) {
    lab_s <- cs_ml_canonical(find(grid[i])$labels)
    ks[i] <- max(lab_s)
    qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
    values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
    values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
    values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
    srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
  }
  what <- if (ALGO == "mcl") "Inflation" else "Resolution"
  tables[[length(tables) + 1L]] <- list(
    key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
    columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
                   list(key = "modularity", label = "Modularity", type = "number")),
    rows = srows
  )
  chosen <- abs(grid - setting) < 1e-12
  charts[[length(charts) + 1L]] <- cs_chart(
    "sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
    list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
         criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
         chosen = cs_col("This run", c(chosen, chosen), "boolean")),
    note = sprintf("The ringed point is this run's %s.", tolower(what))
  )
}

# %% Communities table
crows <- list()
for (c in seq_len(k)) {
  members <- which(labels == c)
  top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
  crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
                     conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
                     examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
  key = "communities", title = "Communities",
  columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
                 list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
                 list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
  rows = crows
)), tables)

# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
  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", "Communities 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("Strength", g$k, "numeric"),
    group = cs_col("Community", as.character(labels), "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))
} else {
  charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
  morder <- order(labels, -g$k, seq_len(N)) - 1L
  charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", 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("Community", as.character(labels), "categorical", level_names),
    order = cs_col("Order", morder, "numeric")
  ), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
                                          controls = list(top = 30))

# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
                   LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
  summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
  title = "Network communities",
  engine = cs_engine_info("nanoparquet", "Matrix"),
  n = N,
  summary = summary,
  statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
                    list(key = "modularity", label = "Modularity", value = values$modularity),
                    list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = artifacts
)
cs_publish(publish)
Python

Leiden found 4 communities among 34 nodes; 73% of the edge weight falls inside them (modularity 0.420).

Communities
4
Modularity
0.4198
Edge weight inside
73.1%

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

Communities

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11235.3%0.2500yes33, 32, 8
21132.4%0.2333yes0, 2, 1
3617.6%0.4167yes31, 23, 27
4514.7%0.2500yes5, 6, 10
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec ab902ef908a98ec8
# 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 ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import communities as cm  # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng

ALGO = "leiden"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 5
DIRECTED = False
SWEEP = False
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)}  # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/leiden_karate/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []

# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl

G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w)  # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
    cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
    cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
    warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
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
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges

# %% Communities
if ALGO in ("leiden", "louvain"):
    if RESOLUTION is not None:
        gamma = float(RESOLUTION)
    elif QUALITY == "cpm":
        gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0)  # the network's density (edge weight per pair of nodes)
    else:
        gamma = 1.0
    values["resolution"] = gamma


def find(setting):
    """Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
    rng = Rng(SEED)
    if ALGO == "leiden":
        r = cm.leiden(g, setting, QUALITY, rng)
    elif ALGO == "louvain":
        r = cm.louvain(g, setting, QUALITY, rng)
    elif ALGO == "label_propagation":
        r = cm.label_propagation(g, rng)
    elif ALGO == "mcl":
        r = cm.mcl(g, setting)
    else:
        fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
        r = cm.infomap(fl, rng, TRIALS)
    return r


setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64))  # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
    values["levels"] = res["levels"]
if "iterations" in res:
    values["iterations"] = res["iterations"]
if "sweeps" in res:
    values["sweeps"] = res["sweeps"]
if "converged" in res:
    values["converged"] = bool(res["converged"])
    if not res["converged"]:
        warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
    values["attractors"] = res["attractors"]
if ALGO == "infomap":
    values["codelength"] = res["codelength"]
    values["codelength_one"] = res["one_module"]

# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
    values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
    warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
    values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
    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, labels[ok])
        values["ami"] = csc.ami(tt, labels[ok])
        values["nmi"] = csc.nmi(tt, labels[ok])

# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
    grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
    srows = []
    for i, s in enumerate(grid, start=1):
        lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
        ks = int(lab_s.max())
        qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
        values[f"sweep_setting[{i}]"] = s
        values[f"sweep_k[{i}]"] = ks
        values[f"sweep_modularity[{i}]"] = qs
        srows.append({"setting": s, "k": ks, "modularity": qs})
    what = "Inflation" if ALGO == "mcl" else "Resolution"
    tables.append({
        "key": "sweep", "title": f"Communities at other settings ({what.lower()})",
        "columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
                    {"key": "modularity", "label": "Modularity", "type": "number"}],
        "rows": srows,
    })
    chosen = [abs(s - setting) < 1e-12 for s in grid]
    charts.append(cs.chart(
        "sweep", "elbow-plot", f"Communities by {what.lower()}",
        {"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
         "criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
         "chosen": cs.col("This run", chosen + chosen, "boolean")},
        note=f"The ringed point is this run's {what.lower()}.",
    ))

# %% Communities table
crows = []
for c in range(1, k + 1):
    members = np.flatnonzero(labels == c)
    top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
    crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
                  "conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
                  "examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
    "key": "communities", "title": "Communities",
    "columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
                {"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
                {"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
    "rows": crows,
})

# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
    xy = gl.fruchterman_reingold(G, SEED)
    m = len(G.si)
    show = min(m, 20000)
    charts.append(cs.chart("map", "network-graph", "Communities 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("Strength", g.k, "numeric"),
        "group": cs.col("Community", [str(c) for c in labels], "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."))
else:
    charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
    morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
    charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
        "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("Community", [str(c) for c in labels], "categorical", level_names),
        "order": cs.col("Order", morder, "numeric"),
    }, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
                       controls={"top": 30}))

# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
           f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
    summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
    "title": "Network communities",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": N,
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Communities", "value": k, "format": "integer"},
        {"key": "modularity", "label": "Modularity", "value": values["modularity"]},
        {"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": artifacts,
}
cs.publish(publish)

Predict first

Leiden reaches a modularity of 0.420 on the karate club. A colleague's partition scores a little higher. Is theirs closer to the real social groups?

Yes: higher modularity means truer communitiesNo: modularity has many near-best partitions and a resolution limit
Reveal

No. Modularity has many partitions with almost the same score, and a resolution limit that can merge small real groups. Compare partitions at the same resolution, check stability over seeds, and judge them against what the communities are for.

07

Infomap: compress the walk

Read

InfomapInfomapFinds network communities as the modules that let you describe a random walker's path in the fewest bits (the map equation). asks how briefly you could describe a random walker's path if each community had its own codebook. The map equation L(M)=q↷H(Q)+∑cpc↻H(Pc)L(M)=q_{\curvearrowright}H(Q)+\sum_c p_c^{\circlearrowright}H(P_c) adds the cost of naming community changes to the cost of naming nodes inside each community.

Network communitiesRecorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

Infomap found 4 communities among 36 nodes; 74% of the edge weight falls inside them (modularity 0.468). The map describes the walk in 4.548 bits per step, against 5.075 with one module.

Communities
4
Modularity
0.4675
Edge weight inside
74.0%

Plots

Communities in the networkWho is connected to whom, which groups hang together and which nodes sit at the center?
View data
FromCommunityNodeStrengthToWeightxy
01p016.95052.3000.2119−0.2408
01p029.24061.960−0.1900−0.6998
01p0311.550111.130−0.1845−0.4055
01p046.290150.5200−0.4254−0.4638
01p057.050321.040−0.1812−1
11p0612.16021.8200.0352−0.5426
11p075.45031.6100.1284−0.7370
11p085.17042.390−0.2899−0.5076
11p094.77051.920−0.3873−0.7101
11p109.65090.8100−0.2812−0.7735
11p113.200110.6900−0.0229−0.7698
21p1212.73050.9800−0.0552−0.3536
22p138.20061.8800.05550.8281
22p144.23081.1100.58210.9136
22p1511.95091.6400.04460.6711
22p1611.500101.5700.06720.2631
22p175.770211.100−0.21580.7160
22p183.470330.69000.23460.9191
22p198.260350.7600−0.18140.5104
32p2010.05070.82000.26840.5586
32p2113.32080.5300−0.02260.4294
32p224.74091.820−0.30910.2217
32p2310.230291.5100.08620.5238
42p244.50061.6100.35930.7552
44p2511.87080.7500−0.2040−0.0692
43p266.14092.3000.10020.1600
53p277.21070.52000.3560−0.2187
53p2811.15091.9600.02840.0103
54p299.300262.180−0.1032−0.1302
53p3013.550312.300−0.12580.0778
73p316.96091.1200.18350.0367
74p327.070111.4300.0758−0.2869
73p337.030241.2800.22970.2908
84p348.950112.3800.1095−0.0263
103p355.290111.6300.35880.0270
114p368.810151.990−0.33560.0227
11———282.330——
11———301.150——
12———161.980——
12———171.480——
12———181.950——
12———191.160——
12———220.8900——
12———230.7400——
13———192.450——
13———231.780——
14———152.260——
14———160.8700——
14———181.010——
14———192.470——
14———202.440——
14———222.250——
14———230.6500——
15———182.200——
15———191.450——
15———201.030——
15———222.050——
16———211.770——
16———221.150——
17———201.990——

First 60 of 98 rows.

Adjacency matrix by communityWhich nodes link to which, and do groups form blocks of dense ties?

Nodes sorted by community: dense blocks on the diagonal are communities.

View data
ColumnCommunityNodeOrderRowWeight
51p011102.300
61p02501.960
111p03201.130
151p04900.5200
321p05101.040
21p06411.820
31p07011.610
41p08312.390
51p09611.920
91p10710.8100
111p11810.6900
51p121020.9800
62p132021.880
82p141421.110
92p151521.640
102p162221.570
212p171921.100
332p181820.6900
352p191220.7600
72p201630.8200
82p212130.5300
92p222331.820
292p231331.510
62p241741.610
84p252940.7500
93p262742.300
73p272650.5200
93p283251.960
264p293052.180
313p302552.300
93p313471.120
114p322471.430
243p332871.280
114p343382.380
113p3535101.630
154p3631111.990
28———112.330
30———111.150
16———121.980
17———121.480
18———121.950
19———121.160
22———120.8900
23———120.7400
19———132.450
23———131.780
15———142.260
16———140.8700
18———141.010
19———142.470
20———142.440
22———142.250
23———140.6500
18———152.200
19———151.450
20———151.030
22———152.050
21———161.770
22———161.150
20———171.990

First 60 of 98 rows.

Community sizesHow often does each category occur?
View data
Community
1
1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
2
2
4
3
3
3
4
3
3
4
3
4
3
4

Communities

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11233.3%0.1789yesp12, p06, p03
21233.3%0.1584yesp21, p15, p16
3719.4%0.3752yesp30, p28, p27
4513.9%0.4935yesp25, p29, p34
  • 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.
The exact R script · R R version 4.5.1 (2025-06-13)
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec faa9518d945125f0
# 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_comm_*(): twin of codesplash.ml.communities

ALGO <- "infomap"
QUALITY <- "modularity"
RESOLUTION <- NULL
INFLATION <- 2
TRIALS <- 5L
DIRECTED <- FALSE
SWEEP <- FALSE
SEED <- 42
LABELS <- c(leiden = "Leiden", louvain = "Louvain", label_propagation = "Label propagation", mcl = "Markov clustering", infomap = "Infomap")
LIMITS <- list(infomap = c(10000, 100000), mcl = c(5000, 50000)) # (nodes, edges); the others 20,000 / 200,000
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.communities/infomap_blocks/out-r")
warnings <- list()
values <- list(algorithm_label = LABELS[[ALGO]])
tables <- list()
charts <- list()
artifacts <- list()

# %% The network the host built (canonical node order, merged edges; cs_graph_read)
G <- cs_graph_read(out)
warnings <- c(warnings, as.list(G$warnings))
N <- G$n
pairs <- cs_graph_undirected_pairs(G)
g <- cs_ml_comm_graph(N, pairs$a + 1L, pairs$b + 1L, pairs$w) # direction set aside: every edge counts both ways
lim <- if (!is.null(LIMITS[[ALGO]])) LIMITS[[ALGO]] else c(20000, 200000)
if (N > lim[1] || length(pairs$a) > lim[2]) {
  cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes = N, n_edges = length(pairs$a), max_nodes = lim[1], max_edges = lim[2])
}
if (N < 2 || g$m2 <= 0) cs_error("CS_E_UNDEFINED", what = "Communities", reason = "the network needs at least one edge between two different nodes")
if (isTRUE(G$directed) && !(ALGO == "infomap" && isTRUE(DIRECTED))) {
  warnings <- c(warnings, sprintf("%s treats every edge as two-way, so the directions were set aside.", LABELS[[ALGO]]))
}
truth <- NULL
if (!is.null(G$label)) truth <- as.character(G$nodes[[G$label]])
values$mode <- "network"
values$n_nodes <- N
values$n_edges <- length(g$idx) %/% 2L

# %% Communities
if (ALGO %in% c("leiden", "louvain")) {
  gamma <- if (!is.null(RESOLUTION)) as.numeric(RESOLUTION) else if (QUALITY == "cpm") (g$m2 / 2) / (N * (N - 1) / 2) else 1 # Potts default: the network's density
  values$resolution <- gamma
}

find <- function(setting) {
  rng <- cs_rng(SEED) # a fresh stream for every setting
  if (ALGO == "leiden") return(cs_ml_comm_leiden(g, setting, QUALITY, rng))
  if (ALGO == "louvain") return(cs_ml_comm_louvain(g, setting, QUALITY, rng))
  if (ALGO == "label_propagation") return(cs_ml_comm_label_propagation(g, rng))
  if (ALGO == "mcl") return(cs_ml_comm_mcl(g, setting))
  fl <- if (isTRUE(G$directed) && isTRUE(DIRECTED)) cs_ml_comm_flow_directed(cs_ml_comm_dgraph(N, G$si + 1L, G$sj + 1L, G$sw)) else cs_ml_comm_flow_undirected(g)
  cs_ml_comm_infomap(fl, rng, TRIALS)
}

setting <- if (ALGO %in% c("leiden", "louvain")) gamma else if (ALGO == "mcl") as.numeric(INFLATION) else NULL
res <- find(setting)
labels <- cs_ml_canonical(res$labels) # 1..k by size, ties by first node
k <- max(labels)
values$k <- k
if (!is.null(res$levels)) values$levels <- res$levels
if (!is.null(res$iterations)) values$iterations <- res$iterations
if (!is.null(res$sweeps)) values$sweeps <- res$sweeps
if (!is.null(res$converged)) {
  values$converged <- isTRUE(res$converged)
  if (!isTRUE(res$converged)) warnings <- c(warnings, sprintf("%s stopped at its iteration limit before every node settled.", LABELS[[ALGO]]))
}
if (!is.null(res$attractors)) values$attractors <- res$attractors
if (ALGO == "infomap") {
  values$codelength <- res$codelength
  values$codelength_one <- res$one_module
}

# %% Quality of the partition
values$modularity <- cs_ml_comm_modularity(g, labels, 1)
if (ALGO %in% c("leiden", "louvain")) {
  values$quality <- if (QUALITY == "cpm") cs_ml_comm_cpm(g, labels, gamma) else cs_ml_comm_modularity(g, labels, gamma)
}
values$coverage <- cs_ml_comm_coverage(g, labels)
cond <- cs_ml_comm_conductance(g, labels)
finite <- cond[!is.nan(cond)]
if (length(finite)) values$conductance <- mean(finite) else values["conductance"] <- list(NULL)
conn <- cs_ml_comm_connected(g, labels)
values$n_disconnected <- sum(!conn)
if (values$n_disconnected > 0) warnings <- c(warnings, sprintf("%d of %d communities fall apart into separate pieces of the network.", values$n_disconnected, k))
sizes <- tabulate(labels, nbins = k)
for (c in seq_len(k)) values[[sprintf("size[%d]", c)]] <- sizes[c]
values$largest_share <- max(sizes) / N
values$singletons <- sum(sizes == 1)
if (!is.null(truth)) {
  ok <- !is.na(truth)
  values$n_labeled <- sum(ok)
  if (sum(ok) >= 2) {
    values$ari <- cs_ml_ari(truth[ok], labels[ok])
    values$ami <- cs_ml_ami(truth[ok], labels[ok])
    values$nmi <- cs_ml_nmi(truth[ok], labels[ok])
  }
}

# %% Settings compared
if (isTRUE(SWEEP) && ALGO %in% c("leiden", "louvain", "mcl")) {
  grid <- if (ALGO != "mcl") gamma * c(0.25, 0.5, 1, 2, 4) else c(1.4, 1.6, 2, 2.5, 3, 4)
  srows <- list(); ks <- integer(0); qs <- numeric(0)
  for (i in seq_along(grid)) {
    lab_s <- cs_ml_canonical(find(grid[i])$labels)
    ks[i] <- max(lab_s)
    qs[i] <- cs_ml_comm_modularity(g, lab_s, 1)
    values[[sprintf("sweep_setting[%d]", i)]] <- grid[i]
    values[[sprintf("sweep_k[%d]", i)]] <- ks[i]
    values[[sprintf("sweep_modularity[%d]", i)]] <- qs[i]
    srows[[i]] <- list(setting = grid[i], k = ks[i], modularity = qs[i])
  }
  what <- if (ALGO == "mcl") "Inflation" else "Resolution"
  tables[[length(tables) + 1L]] <- list(
    key = "sweep", title = sprintf("Communities at other settings (%s)", tolower(what)),
    columns = list(list(key = "setting", label = what, type = "number"), list(key = "k", label = "Communities", type = "integer"),
                   list(key = "modularity", label = "Modularity", type = "number")),
    rows = srows
  )
  chosen <- abs(grid - setting) < 1e-12
  charts[[length(charts) + 1L]] <- cs_chart(
    "sweep", "elbow-plot", sprintf("Communities by %s", tolower(what)),
    list(k = cs_col(what, c(grid, grid), "numeric"), score = cs_col("Value", c(ks, qs), "numeric"),
         criterion = cs_col("Measure", c(rep("Communities", length(grid)), rep("Modularity", length(grid))), "categorical", c("Communities", "Modularity")),
         chosen = cs_col("This run", c(chosen, chosen), "boolean")),
    note = sprintf("The ringed point is this run's %s.", tolower(what))
  )
}

# %% Communities table
crows <- list()
for (c in seq_len(k)) {
  members <- which(labels == c)
  top <- members[order(-g$k[members], members)][seq_len(min(3L, length(members)))]
  crows[[c]] <- list(community = c, size = sizes[c], share = sizes[c] / N,
                     conductance = if (is.nan(cond[c])) NULL else cond[c], connected = conn[c],
                     examples = paste(G$node_id[top], collapse = ", "))
}
tables <- c(list(list(
  key = "communities", title = "Communities",
  columns = list(list(key = "community", label = "Community", type = "integer"), list(key = "size", label = "Nodes", type = "integer"),
                 list(key = "share", label = "Share", type = "percent"), list(key = "conductance", label = "Conductance", type = "number"),
                 list(key = "connected", label = "In one piece", type = "boolean"), list(key = "examples", label = "Best-connected nodes")),
  rows = crows
)), tables)

# %% Results per node (or row) and charts
level_names <- as.character(seq_len(k))
artifacts[[length(artifacts) + 1L]] <- cs_graph_write_nodes(out, G, data.frame(community = as.integer(labels), strength = g$k))
MAP_NODES <- 2000; MATRIX_NODES <- 300
if (N <= MAP_NODES) {
  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", "Communities 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("Strength", g$k, "numeric"),
    group = cs_col("Community", as.character(labels), "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))
} else {
  charts[[length(charts) + 1L]] <- cs_chart("map", "network-graph", "Communities in the network", list(), note = sprintf("The map is drawn for networks up to %d nodes; this one has %d.", MAP_NODES, N))
}
if (N <= MATRIX_NODES) {
  morder <- order(labels, -g$k, seq_len(N)) - 1L
  charts[[length(charts) + 1L]] <- cs_chart("matrix", "adjacency-matrix", "Adjacency matrix by community", 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("Community", as.character(labels), "categorical", level_names),
    order = cs_col("Order", morder, "numeric")
  ), controls = list(directed = isTRUE(G$directed)), note = "Nodes sorted by community: dense blocks on the diagonal are communities.")
}
charts[[length(charts) + 1L]] <- cs_chart("sizes", "bar", "Community sizes", list(x = cs_col("Community", as.character(labels), "categorical", level_names)),
                                          controls = list(top = 30))

# %% Result
what <- if (values$mode == "rows") "rows" else "nodes"
summary <- sprintf("%s found %d communit%s among %s %s; %.0f%% of the edge weight falls inside them (modularity %.3f).",
                   LABELS[[ALGO]], k, if (k == 1) "y" else "ies", format(N, big.mark = ","), what, 100 * values$coverage, values$modularity)
if (ALGO == "infomap") {
  summary <- paste0(summary, sprintf(" The map describes the walk in %.3f bits per step, against %.3f with one module.", values$codelength, values$codelength_one))
}
publish <- list(
  title = "Network communities",
  engine = cs_engine_info("nanoparquet", "Matrix"),
  n = N,
  summary = summary,
  statistics = list(list(key = "k", label = "Communities", value = k, format = "integer"),
                    list(key = "modularity", label = "Modularity", value = values$modularity),
                    list(key = "coverage", label = "Edge weight inside", value = values$coverage, format = "percent")),
  tables = tables,
  values = values,
  charts = charts,
  warnings = warnings,
  artifacts = artifacts
)
cs_publish(publish)
Python

Infomap found 4 communities among 36 nodes; 74% of the edge weight falls inside them (modularity 0.468). The map describes the walk in 4.548 bits per step, against 5.075 with one module.

Communities
4
Modularity
0.4675
Edge weight inside
74.0%

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

Communities

CommunityNodesShareConductanceIn one pieceBest-connected nodes
11233.3%0.1789yesp12, p06, p03
21233.3%0.1584yesp21, p15, p16
3719.4%0.3752yesp30, p28, p27
4513.9%0.4935yesp25, p29, p34
  • 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.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Network communities
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.communities 1.0.0 · spec faa9518d945125f0
# 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 ml as csml
from codesplash.ml import cluster as csc
from codesplash.ml import communities as cm  # twin of codesplashr R/ml_communities.R
from codesplash.stats.rng import Rng

ALGO = "infomap"
QUALITY = "modularity"
RESOLUTION = None
INFLATION = 2
TRIALS = 5
DIRECTED = False
SWEEP = False
SEED = 42
LABELS = {"leiden": "Leiden", "louvain": "Louvain", "label_propagation": "Label propagation", "mcl": "Markov clustering", "infomap": "Infomap"}
LIMITS = {"infomap": (10000, 100000), "mcl": (5000, 50000)}  # (nodes, edges); the others 20,000 / 200,000
out = csml.out_dir("target/academy-parity/run-8142/discover.communities/infomap_blocks/out-python")
warnings = []
values = {"algorithm_label": LABELS[ALGO]}
tables = []
charts = []
artifacts = []

# %% The network the host built (canonical node order, merged edges; codesplash.graph)
from codesplash import graph as cg
from codesplash.graph import layout as gl

G = cg.read(out)
warnings += list(G.warnings)
N = G.n
a, b, w = cg.undirected_pairs(G)
g = cm.undirected(N, a, b, w)  # direction set aside: every edge counts both ways
max_nodes, max_edges = LIMITS.get(ALGO, (20000, 200000))
if N > max_nodes or len(a) > max_edges:
    cs.cs_error("CS_E_GRAPH_TOO_LARGE", n_nodes=N, n_edges=len(a), max_nodes=max_nodes, max_edges=max_edges)
if N < 2 or g.m2 <= 0:
    cs.cs_error("CS_E_UNDEFINED", what="Communities", reason="the network needs at least one edge between two different nodes")
if G.directed and not (ALGO == "infomap" and DIRECTED):
    warnings.append(f"{LABELS[ALGO]} treats every edge as two-way, so the directions were set aside.")
truth = None
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
values["mode"] = "network"
values["n_nodes"] = N
values["n_edges"] = g.n_edges

# %% Communities
if ALGO in ("leiden", "louvain"):
    if RESOLUTION is not None:
        gamma = float(RESOLUTION)
    elif QUALITY == "cpm":
        gamma = (g.m2 / 2.0) / (N * (N - 1) / 2.0)  # the network's density (edge weight per pair of nodes)
    else:
        gamma = 1.0
    values["resolution"] = gamma


def find(setting):
    """Communities for one setting (resolution or inflation), from a fresh stream → (labels, info)."""
    rng = Rng(SEED)
    if ALGO == "leiden":
        r = cm.leiden(g, setting, QUALITY, rng)
    elif ALGO == "louvain":
        r = cm.louvain(g, setting, QUALITY, rng)
    elif ALGO == "label_propagation":
        r = cm.label_propagation(g, rng)
    elif ALGO == "mcl":
        r = cm.mcl(g, setting)
    else:
        fl = cm.flow_directed(cm.DGraph(N, G.si, G.sj, G.sw)) if (G.directed and DIRECTED) else cm.flow_undirected(g)
        r = cm.infomap(fl, rng, TRIALS)
    return r


setting = gamma if ALGO in ("leiden", "louvain") else (float(INFLATION) if ALGO == "mcl" else None)
res = find(setting)
labels = csc.canonical(np.asarray(res["labels"], dtype=np.int64))  # 1…k by size, ties by first node
lab0 = (labels - 1).tolist()
k = int(labels.max())
values["k"] = k
if "levels" in res:
    values["levels"] = res["levels"]
if "iterations" in res:
    values["iterations"] = res["iterations"]
if "sweeps" in res:
    values["sweeps"] = res["sweeps"]
if "converged" in res:
    values["converged"] = bool(res["converged"])
    if not res["converged"]:
        warnings.append(f"{LABELS[ALGO]} stopped at its iteration limit before every node settled.")
if "attractors" in res:
    values["attractors"] = res["attractors"]
if ALGO == "infomap":
    values["codelength"] = res["codelength"]
    values["codelength_one"] = res["one_module"]

# %% Quality of the partition
values["modularity"] = cm.modularity(g, lab0, 1.0)
if ALGO in ("leiden", "louvain"):
    values["quality"] = cm.cpm(g, lab0, gamma) if QUALITY == "cpm" else cm.modularity(g, lab0, gamma)
values["coverage"] = cm.coverage(g, lab0)
cond = cm.conductance(g, lab0)
finite = [c for c in cond if c == c]
values["conductance"] = float(np.mean(finite)) if finite else None
conn = cm.connected(g, lab0)
values["n_disconnected"] = int(sum(1 for x in conn if not x))
if values["n_disconnected"]:
    warnings.append(f"{values['n_disconnected']} of {k} communities fall apart into separate pieces of the network.")
sizes = np.bincount(labels, minlength=k + 1)[1:]
for c in range(1, k + 1):
    values[f"size[{c}]"] = int(sizes[c - 1])
values["largest_share"] = float(sizes.max() / N)
values["singletons"] = int(np.sum(sizes == 1))
if truth is not None:
    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, labels[ok])
        values["ami"] = csc.ami(tt, labels[ok])
        values["nmi"] = csc.nmi(tt, labels[ok])

# %% Settings compared
if SWEEP and ALGO in ("leiden", "louvain", "mcl"):
    grid = [gamma * f for f in (0.25, 0.5, 1.0, 2.0, 4.0)] if ALGO != "mcl" else [1.4, 1.6, 2.0, 2.5, 3.0, 4.0]
    srows = []
    for i, s in enumerate(grid, start=1):
        lab_s = csc.canonical(np.asarray(find(s)["labels"], dtype=np.int64))
        ks = int(lab_s.max())
        qs = cm.modularity(g, (lab_s - 1).tolist(), 1.0)
        values[f"sweep_setting[{i}]"] = s
        values[f"sweep_k[{i}]"] = ks
        values[f"sweep_modularity[{i}]"] = qs
        srows.append({"setting": s, "k": ks, "modularity": qs})
    what = "Inflation" if ALGO == "mcl" else "Resolution"
    tables.append({
        "key": "sweep", "title": f"Communities at other settings ({what.lower()})",
        "columns": [{"key": "setting", "label": what, "type": "number"}, {"key": "k", "label": "Communities", "type": "integer"},
                    {"key": "modularity", "label": "Modularity", "type": "number"}],
        "rows": srows,
    })
    chosen = [abs(s - setting) < 1e-12 for s in grid]
    charts.append(cs.chart(
        "sweep", "elbow-plot", f"Communities by {what.lower()}",
        {"k": cs.col(what, grid + grid, "numeric"), "score": cs.col("Value", [r["k"] for r in srows] + [r["modularity"] for r in srows], "numeric"),
         "criterion": cs.col("Measure", ["Communities"] * len(grid) + ["Modularity"] * len(grid), "categorical", ["Communities", "Modularity"]),
         "chosen": cs.col("This run", chosen + chosen, "boolean")},
        note=f"The ringed point is this run's {what.lower()}.",
    ))

# %% Communities table
crows = []
for c in range(1, k + 1):
    members = np.flatnonzero(labels == c)
    top = sorted(members.tolist(), key=lambda v: (-g.k[v], v))[:3]
    crows.append({"community": c, "size": int(sizes[c - 1]), "share": float(sizes[c - 1] / N),
                  "conductance": cond[c - 1] if cond[c - 1] == cond[c - 1] else None, "connected": bool(conn[c - 1]),
                  "examples": ", ".join(G.node_id[v] for v in top)})
tables.insert(0, {
    "key": "communities", "title": "Communities",
    "columns": [{"key": "community", "label": "Community", "type": "integer"}, {"key": "size", "label": "Nodes", "type": "integer"},
                {"key": "share", "label": "Share", "type": "percent"}, {"key": "conductance", "label": "Conductance", "type": "number"},
                {"key": "connected", "label": "In one piece", "type": "boolean"}, {"key": "examples", "label": "Best-connected nodes"}],
    "rows": crows,
})

# %% Results per node (or row) and charts
level_names = [str(c) for c in range(1, k + 1)]
cols = {"community": labels.astype(np.int64), "strength": np.asarray(g.k, dtype=np.float64)}
artifacts.append(cg.write_nodes(out, G, cols))
MAP_NODES, MATRIX_NODES = 2000, 300
if N <= MAP_NODES:
    xy = gl.fruchterman_reingold(G, SEED)
    m = len(G.si)
    show = min(m, 20000)
    charts.append(cs.chart("map", "network-graph", "Communities 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("Strength", g.k, "numeric"),
        "group": cs.col("Community", [str(c) for c in labels], "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."))
else:
    charts.append(cs.chart("map", "network-graph", "Communities in the network", {}, note=f"The map is drawn for networks up to {MAP_NODES} nodes; this one has {N}."))
if N <= MATRIX_NODES:
    morder = sorted(range(N), key=lambda v: (int(labels[v]), -g.k[v], v))
    charts.append(cs.chart("matrix", "adjacency-matrix", "Adjacency matrix by community", {
        "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("Community", [str(c) for c in labels], "categorical", level_names),
        "order": cs.col("Order", morder, "numeric"),
    }, controls={"directed": G.directed}, note="Nodes sorted by community: dense blocks on the diagonal are communities."))
charts.append(cs.chart("sizes", "bar", "Community sizes", {"x": cs.col("Community", [str(c) for c in labels], "categorical", level_names)},
                       controls={"top": 30}))

# %% Result
what = "rows" if values["mode"] == "rows" else "nodes"
summary = (f"{LABELS[ALGO]} found {k} communit{'y' if k == 1 else 'ies'} among {N:,} {what}; "
           f"{values['coverage']:.0%} of the edge weight falls inside them (modularity {values['modularity']:.3f}).")
if ALGO == "infomap":
    summary += f" The map describes the walk in {values['codelength']:.3f} bits per step, against {values['codelength_one']:.3f} with one module."
publish = {
    "title": "Network communities",
    "engine": cs.engine_info("numpy", "pandas", "scipy"),
    "n": N,
    "summary": summary,
    "statistics": [
        {"key": "k", "label": "Communities", "value": k, "format": "integer"},
        {"key": "modularity", "label": "Modularity", "value": values["modularity"]},
        {"key": "coverage", "label": "Edge weight inside", "value": values["coverage"], "format": "percent"},
    ],
    "tables": tables,
    "values": values,
    "charts": charts,
    "warnings": warnings,
    "artifacts": artifacts,
}
cs.publish(publish)

The best partition needed 4.55 bits per step against 5.07 for one big module. Infomap follows edge directions, so it suits flows (traffic, citations, money) and can disagree with modularity, which ignores them. Check that a walk along your edges means something.

08

Correlation clustering: honor the judgments

Read

Correlation clusteringCorrelation clusteringTurns pairwise same/different judgments into a partition that breaks as few weighted judgments as possible; the cluster count falls out. starts from pairwise judgments: positive edges say "same", negative edges say "different". It minimizes the weighted number of broken judgments, ∑E+wij1(zi≠zj)+∑E−wij1(zi=zj)\sum_{E^+} w_{ij}\mathbf 1(z_i\ne z_j)+\sum_{E^-} w_{ij}\mathbf 1(z_i=z_j), and the number of clusters falls out.

Judgments needn't be consistent (A = B, B = C, A ≠ C), but a partition is: in the reference's three-node example, the best grouping still breaks 1 judgment. Its home is entity resolution, where false merges and false splits cost different things: inspect both, not only the total.

09

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Spectral clustering (UCL027)Runs in CodeSplash: Spectral clustering (nearest-neighbor or RBF graph from columns)
Markov clustering (UCL028)Runs in CodeSplash (Experimental): Network communities, Algorithm MCL
Chinese Whispers (UCL029)Runs in CodeSplash (Experimental): Network communities, Algorithm Label propagation
Louvain (UCL030)Runs in CodeSplash (Experimental): Network communities, Algorithm Louvain
Leiden (UCL031)Runs in CodeSplash (Experimental): Network communities, Algorithm Leiden, modularity or CPM
Infomap (UCL032)Runs in CodeSplash (Experimental): Network communities, Algorithm Infomap
Correlation clustering (UCL033)Explained here

Network communities reads an edge list, or links table rows to their nearest neighbors.

Reference · UCL033 · Explained hereCorrelation clusteringReconcile pairwise evidence that objects should be together or apart, without fixing the number of clusters. Useful for entity resolution, record linkage, and signed-network partitioning when similarity judgments may…
10

Check your understanding

Checkpoint

Check yourself

The eigengap suggests eight clusters, but two clusters match the known structure exactly. What should you make of the eigengap?

Show the answer

Answer: b

Eigengaps help pick kk but don't test anything. Graph construction and disconnected pieces can create misleading gaps.

Check yourself

What usually has the biggest influence on spectral clustering's result?

Show the answer

Answer: b

The Laplacian only sees the graph. Change the neighbors or the kernel width and the cut changes.

Check yourself

You raise MCL's inflation. What happens?

Show the answer

Answer: a

Inflation sharpens flow toward strong connections and sets the granularity. Compare results across a few inflation values.

Check yourself

What kind of method is Markov clustering?

Show the answer

Answer: b

MCL simulates random-walk flow and sharpens it. It has no likelihood, so its communities don't come with probabilities.

Check yourself

Two runs of Chinese Whispers on the same graph give different labels. Why?

Show the answer

Answer: b

Asynchronous updates make the result depend on the visit order. Compare runs with partition agreement and report nodes that switch.

Check yourself

What can a dominant hub do in Chinese Whispers?

Show the answer

Answer: a

Majority voting rewards well-connected nodes, so a hub's label can flood its neighborhood. Disconnected pieces, on the other hand, can never share a label.

Check yourself

What weakness of Louvain led to Leiden?

Show the answer

Answer: b

Leiden adds a refinement step that keeps each community in one piece.

Check yourself

What does modularity compare?

Show the answer

Answer: a

Aij−γkikj/(2m)A_{ij}-\gamma k_ik_j/(2m): observed links minus links you'd expect from degrees. A positive total means denser-than-chance communities, not proven ones.

Check yourself

You found a good resolution with Leiden on modularity and switch to the constant Potts model. Can you keep the same resolution number?

Show the answer

Answer: b

Modularity's γ scales expected edges by degree; CPM's γ scales pairs of nodes. Tune each separately, and look for communities that persist over a range.

Check yourself

Leiden guarantees connected communities. What does that guarantee not tell you?

Show the answer

Answer: b

Connectivity is a useful property, not a certificate of truth. Check seed stability and persistence across resolutions.

Check yourself

When is Infomap a better fit than modularity?

Show the answer

Answer: a

Infomap models a random walker along the edges and follows directions. Modularity counts edges and ignores where flow goes.

Check yourself

Infomap's partition has a shorter code length than one single module. What does that mean?

Show the answer

Answer: b

A shorter description means flow is trapped in modules. Compare code lengths only under the same flow assumptions.

Check yourself

What does correlation clustering minimize?

Show the answer

Answer: b

It turns pairwise judgments into a partition and chooses the number of clusters itself.

Check yourself

In entity resolution with correlation clustering, why isn't a low total disagreement enough?

Show the answer

Answer: b

The two error types cost different things. Report errors by type and check how uncertain judgments change the clusters.

11

Do it on your own data

In the app

Load an edge list and open Network communities under Find segments: start with Leiden, try two resolutions, then Infomap if your edges have directions. For a table without edges, Spectral clustering or the communities method's nearest-neighbor mode groups the rows.

Concepts in this lesson