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.
What runs in CodeSplash
- UCL027Spectral clustering Runs in CodeSplash
- UCL028Markov clustering (MCL) Runs in CodeSplash (Experimental)
- UCL029Chinese Whispers Runs in CodeSplash (Experimental)
- UCL030Louvain community detection Runs in CodeSplash (Experimental)
- UCL031Leiden community detection Runs in CodeSplash (Experimental)
- UCL032Infomap Runs in CodeSplash (Experimental)
- UCL033Correlation clustering Explained here
- Spectral clustering Verified in Python and R
- Network communities Experimental
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
Same graph, different questions
ReadA 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:
| Method | A good community is… |
|---|---|
| Spectral clustering | a set with few edges cut to the rest, relative to its size |
| Markov clustering, Infomap | a place a random walk stays trapped |
| Chinese Whispers | a set where each node shares its neighbors' majority label |
| Louvain, Leiden | denser inside than the degrees alone predict (modularity) |
| Correlation clustering | a grouping that breaks the fewest "same" and "different" judgments |
Pick the question first; the answers can differ on the same graph.
Spectral clustering: relax a cut
ReadFrom an affinity matrix and degrees , spectral clustering takes the eigenvectors of the normalized Laplacian with the smallest eigenvalues and clusters their rows. Those eigenvectors are a relaxed solution to "cut few edges, keep the parts balanced".
Spectral clustering with k = 2 on a nearest-neighbor graph; the largest eigenvalue gap suggests k = 8.
- Clusters
- 2
- Mean silhouette
- 0.1181
Plots
View data
| Cluster | x | y |
|---|---|---|
| 1 | −1.786 | −0.4692 |
| 2 | −0.2103 | 0.7162 |
| 1 | 0.6283 | 1.552 |
| 2 | −0.4521 | 0.6855 |
| 2 | 0.3024 | 0.2584 |
| 1 | 0.4395 | −1.697 |
| 2 | 0.4331 | −0.0558 |
| 2 | 0.4492 | −0.3593 |
| 2 | −0.4941 | −0.0709 |
| 2 | −0.4685 | −0.5394 |
| 2 | −0.0596 | 0.7036 |
| 2 | −0.7429 | −0.0588 |
| 1 | −1.062 | −1.517 |
| 1 | −0.3127 | 1.659 |
| 2 | −0.4611 | −0.2223 |
| 2 | 0.0235 | 0.5129 |
| 1 | −1.301 | −1.196 |
| 2 | −0.2439 | −0.6075 |
| 2 | −0.6338 | −0.1665 |
| 1 | 0.6791 | −1.553 |
| 2 | −0.6788 | −0.0244 |
| 1 | 0.5619 | 1.673 |
| 1 | −1.808 | −0.5330 |
| 2 | −0.5496 | 0.3045 |
| 2 | −0.2780 | −0.6040 |
| 2 | −0.2550 | 0.7943 |
| 1 | −1.273 | −1.445 |
| 1 | 0.0430 | −1.968 |
| 2 | −0.0387 | −0.6561 |
| 2 | 0.3572 | 0.2670 |
| 2 | −0.5418 | −0.2096 |
| 1 | −1.222 | −1.386 |
| 1 | 0.0128 | −1.606 |
| 1 | −1.266 | −1.102 |
| 1 | 1.488 | −0.5147 |
| 1 | 1.722 | 0.3375 |
| 2 | −0.2139 | −0.5705 |
| 1 | 0.4204 | −1.897 |
| 2 | −0.4659 | −0.4211 |
| 1 | −1.854 | 0.4413 |
| 1 | 1.742 | 0.0514 |
| 1 | −0.2564 | −1.645 |
| 1 | 0.7345 | −1.555 |
| 1 | 0.3494 | 1.599 |
| 1 | 0.9373 | −1.515 |
| 2 | −0.5004 | 0.4092 |
| 2 | −0.4703 | −0.6429 |
| 2 | −0.3817 | −0.5890 |
| 1 | −1.078 | −1.501 |
| 2 | 0.4095 | 0.1630 |
| 2 | −0.5402 | −0.4220 |
| 1 | 1.534 | −1.208 |
| 1 | 0.8112 | 1.521 |
| 2 | 0.2235 | −0.5717 |
| 1 | 0.6529 | −1.479 |
| 1 | 0.9315 | −1.534 |
| 1 | 1.306 | 0.9765 |
| 1 | 1.271 | 1.018 |
| 1 | 1.416 | 0.9223 |
| 1 | 0.4963 | −1.663 |
First 60 of 300 rows.
The largest gap after eigenvalue 8 suggests k = 8.
View data
| Largest gap | Eigenvalue (rank) | Eigenvalue |
|---|---|---|
| false | 1 | 1 |
| false | 2 | 1 |
| false | 3 | 0.9940 |
| false | 4 | 0.9936 |
| false | 5 | 0.9825 |
| false | 6 | 0.9816 |
| false | 7 | 0.9777 |
| true | 8 | 0.9734 |
| false | 9 | 0.9506 |
| false | 10 | 0.9430 |
View data
| Cluster | Silhouette 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
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 180 | 60.0% | 0.2747 | 0.0557 |
| 2 | 120 | 40.0% | −0.0334 | 0.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"
))
))
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
| Cluster | Size | Share | x | y |
|---|---|---|---|---|
| 1 | 180 | 60.0% | 0.2747 | 0.0557 |
| 2 | 120 | 40.0% | −0.0334 | 0.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.
Cut a neighbor graph
ExploreAExplorable · 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?
Data
Commit your prediction above to see the result
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.
Random walks: MCL and Chinese Whispers
ReadMarkov 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 and alternates expansion, (walk further), with inflation, raising entries to a power 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, . It's fast and needs no , but the visit order matters: compare repeated runs and report the unstable nodes.
Modularity: Louvain and Leiden
ReadModularityModularityThe 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: . The resolution sets the scale: on a block graph, = 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 across objectives.
A higher modularity
PredictLeiden 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
View data
| From | Community | Node | Strength | To | x | y |
|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 16 | 1 | −0.3181 | −0.2545 |
| 0 | 2 | 1 | 9 | 2 | −0.2233 | −0.0757 |
| 0 | 4 | 10 | 3 | 3 | −0.5988 | −0.5538 |
| 0 | 2 | 11 | 1 | 4 | −0.7684 | −0.3116 |
| 0 | 2 | 12 | 2 | 5 | −0.5555 | −0.3153 |
| 0 | 2 | 13 | 5 | 9 | −0.0383 | −0.1016 |
| 0 | 1 | 14 | 2 | 11 | 0.6563 | 0.2455 |
| 0 | 1 | 15 | 2 | 12 | 0.5571 | −0.0469 |
| 0 | 4 | 16 | 2 | 14 | −0.5525 | −1 |
| 0 | 2 | 17 | 2 | 23 | −0.5518 | −0.1334 |
| 0 | 1 | 18 | 2 | 25 | 0.6951 | 0.1440 |
| 0 | 2 | 19 | 3 | 28 | −0.1218 | 0.0626 |
| 0 | 2 | 2 | 10 | 29 | −0.0184 | 0.0461 |
| 0 | 1 | 20 | 2 | 30 | 0.6496 | 0.0363 |
| 0 | 2 | 21 | 2 | 31 | −0.5239 | −0.0045 |
| 0 | 1 | 22 | 2 | 32 | 0.6464 | 0.3546 |
| 1 | 3 | 23 | 5 | 5 | 0.3325 | 0.4993 |
| 1 | 3 | 24 | 3 | 9 | −0.0504 | 0.6329 |
| 1 | 3 | 25 | 3 | 11 | 0.1108 | 0.6623 |
| 1 | 1 | 26 | 2 | 12 | 0.6203 | 0.5661 |
| 1 | 3 | 27 | 4 | 14 | 0.1293 | 0.4353 |
| 1 | 3 | 28 | 3 | 23 | 0.1494 | 0.2290 |
| 1 | 1 | 29 | 4 | 24 | 0.5085 | 0.4495 |
| 1 | 2 | 3 | 6 | 31 | −0.2882 | −0.1638 |
| 2 | 1 | 30 | 4 | 28 | 0.2164 | −0.0296 |
| 2 | 3 | 31 | 6 | 29 | 0.0165 | 0.2593 |
| 4 | 1 | 32 | 12 | 23 | 0.4004 | 0.1628 |
| 5 | 1 | 33 | 17 | 12 | 0.3249 | 0.2115 |
| 5 | 4 | 4 | 3 | 23 | −0.4335 | −0.5876 |
| 5 | 4 | 5 | 4 | 27 | −0.5362 | −0.7094 |
| 6 | 4 | 6 | 4 | 26 | −0.4075 | −0.7379 |
| 6 | 2 | 7 | 4 | 27 | −0.1466 | −0.2632 |
| 7 | 1 | 8 | 5 | 26 | 0.1237 | −0.0736 |
| 7 | 1 | 9 | 2 | 27 | −0.0040 | 0.3656 |
| 8 | — | — | — | 29 | — | — |
| 8 | — | — | — | 30 | — | — |
| 10 | — | — | — | 26 | — | — |
| 10 | — | — | — | 27 | — | — |
| 11 | — | — | — | 27 | — | — |
| 12 | — | — | — | 20 | — | — |
| 12 | — | — | — | 21 | — | — |
| 12 | — | — | — | 23 | — | — |
| 12 | — | — | — | 26 | — | — |
| 12 | — | — | — | 31 | — | — |
| 12 | — | — | — | 32 | — | — |
| 12 | — | — | — | 33 | — | — |
| 13 | — | — | — | 26 | — | — |
| 13 | — | — | — | 27 | — | — |
| 15 | — | — | — | 26 | — | — |
| 15 | — | — | — | 27 | — | — |
| 16 | — | — | — | 18 | — | — |
| 16 | — | — | — | 20 | — | — |
| 16 | — | — | — | 22 | — | — |
| 16 | — | — | — | 26 | — | — |
| 16 | — | — | — | 27 | — | — |
| 17 | — | — | — | 18 | — | — |
| 17 | — | — | — | 20 | — | — |
| 17 | — | — | — | 25 | — | — |
| 18 | — | — | — | 25 | — | — |
| 19 | — | — | — | 22 | — | — |
First 60 of 78 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Edge |
|---|---|---|---|---|---|
| 1 | 2 | 0 | 27 | 0 | 1 |
| 2 | 2 | 1 | 26 | 0 | 1 |
| 3 | 4 | 10 | 32 | 0 | 1 |
| 4 | 2 | 11 | 22 | 0 | 1 |
| 5 | 2 | 12 | 24 | 0 | 1 |
| 9 | 2 | 13 | 6 | 0 | 1 |
| 11 | 1 | 14 | 7 | 0 | 1 |
| 12 | 1 | 15 | 10 | 0 | 1 |
| 14 | 4 | 16 | 13 | 0 | 1 |
| 23 | 2 | 17 | 15 | 0 | 1 |
| 25 | 1 | 18 | 19 | 0 | 1 |
| 28 | 2 | 19 | 33 | 0 | 1 |
| 29 | 2 | 2 | 0 | 0 | 1 |
| 30 | 1 | 20 | 12 | 0 | 1 |
| 31 | 2 | 21 | 1 | 0 | 1 |
| 32 | 1 | 22 | 23 | 0 | 1 |
| 5 | 3 | 23 | 5 | 1 | 1 |
| 9 | 3 | 24 | 31 | 1 | 1 |
| 11 | 3 | 25 | 11 | 1 | 1 |
| 12 | 1 | 26 | 4 | 1 | 1 |
| 14 | 3 | 27 | 9 | 1 | 1 |
| 23 | 3 | 28 | 14 | 1 | 1 |
| 24 | 1 | 29 | 3 | 1 | 1 |
| 31 | 2 | 3 | 25 | 1 | 1 |
| 28 | 1 | 30 | 16 | 2 | 1 |
| 29 | 3 | 31 | 20 | 2 | 1 |
| 23 | 1 | 32 | 17 | 4 | 1 |
| 12 | 1 | 33 | 18 | 5 | 1 |
| 23 | 4 | 4 | 21 | 5 | 1 |
| 27 | 4 | 5 | 29 | 5 | 1 |
| 26 | 4 | 6 | 30 | 6 | 1 |
| 27 | 2 | 7 | 2 | 6 | 1 |
| 26 | 1 | 8 | 28 | 7 | 1 |
| 27 | 1 | 9 | 8 | 7 | 1 |
| 29 | — | — | — | 8 | 1 |
| 30 | — | — | — | 8 | 1 |
| 26 | — | — | — | 10 | 1 |
| 27 | — | — | — | 10 | 1 |
| 27 | — | — | — | 11 | 1 |
| 20 | — | — | — | 12 | 1 |
| 21 | — | — | — | 12 | 1 |
| 23 | — | — | — | 12 | 1 |
| 26 | — | — | — | 12 | 1 |
| 31 | — | — | — | 12 | 1 |
| 32 | — | — | — | 12 | 1 |
| 33 | — | — | — | 12 | 1 |
| 26 | — | — | — | 13 | 1 |
| 27 | — | — | — | 13 | 1 |
| 26 | — | — | — | 15 | 1 |
| 27 | — | — | — | 15 | 1 |
| 18 | — | — | — | 16 | 1 |
| 20 | — | — | — | 16 | 1 |
| 22 | — | — | — | 16 | 1 |
| 26 | — | — | — | 16 | 1 |
| 27 | — | — | — | 16 | 1 |
| 18 | — | — | — | 17 | 1 |
| 20 | — | — | — | 17 | 1 |
| 25 | — | — | — | 17 | 1 |
| 25 | — | — | — | 18 | 1 |
| 22 | — | — | — | 19 | 1 |
First 60 of 78 rows.
View data
| 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
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 35.3% | 0.2500 | yes | 33, 32, 8 |
| 2 | 11 | 32.4% | 0.2333 | yes | 0, 2, 1 |
| 3 | 6 | 17.6% | 0.4167 | yes | 31, 23, 27 |
| 4 | 5 | 14.7% | 0.2500 | yes | 5, 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)
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
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 35.3% | 0.2500 | yes | 33, 32, 8 |
| 2 | 11 | 32.4% | 0.2333 | yes | 0, 2, 1 |
| 3 | 6 | 17.6% | 0.4167 | yes | 31, 23, 27 |
| 4 | 5 | 14.7% | 0.2500 | yes | 5, 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?
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.
Infomap: compress the walk
ReadInfomapInfomapFinds 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 adds the cost of naming community changes to the cost of naming nodes inside each community.
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
View data
| From | Community | Node | Strength | To | Weight | x | y |
|---|---|---|---|---|---|---|---|
| 0 | 1 | p01 | 6.950 | 5 | 2.300 | 0.2119 | −0.2408 |
| 0 | 1 | p02 | 9.240 | 6 | 1.960 | −0.1900 | −0.6998 |
| 0 | 1 | p03 | 11.550 | 11 | 1.130 | −0.1845 | −0.4055 |
| 0 | 1 | p04 | 6.290 | 15 | 0.5200 | −0.4254 | −0.4638 |
| 0 | 1 | p05 | 7.050 | 32 | 1.040 | −0.1812 | −1 |
| 1 | 1 | p06 | 12.160 | 2 | 1.820 | 0.0352 | −0.5426 |
| 1 | 1 | p07 | 5.450 | 3 | 1.610 | 0.1284 | −0.7370 |
| 1 | 1 | p08 | 5.170 | 4 | 2.390 | −0.2899 | −0.5076 |
| 1 | 1 | p09 | 4.770 | 5 | 1.920 | −0.3873 | −0.7101 |
| 1 | 1 | p10 | 9.650 | 9 | 0.8100 | −0.2812 | −0.7735 |
| 1 | 1 | p11 | 3.200 | 11 | 0.6900 | −0.0229 | −0.7698 |
| 2 | 1 | p12 | 12.730 | 5 | 0.9800 | −0.0552 | −0.3536 |
| 2 | 2 | p13 | 8.200 | 6 | 1.880 | 0.0555 | 0.8281 |
| 2 | 2 | p14 | 4.230 | 8 | 1.110 | 0.5821 | 0.9136 |
| 2 | 2 | p15 | 11.950 | 9 | 1.640 | 0.0446 | 0.6711 |
| 2 | 2 | p16 | 11.500 | 10 | 1.570 | 0.0672 | 0.2631 |
| 2 | 2 | p17 | 5.770 | 21 | 1.100 | −0.2158 | 0.7160 |
| 2 | 2 | p18 | 3.470 | 33 | 0.6900 | 0.2346 | 0.9191 |
| 2 | 2 | p19 | 8.260 | 35 | 0.7600 | −0.1814 | 0.5104 |
| 3 | 2 | p20 | 10.050 | 7 | 0.8200 | 0.2684 | 0.5586 |
| 3 | 2 | p21 | 13.320 | 8 | 0.5300 | −0.0226 | 0.4294 |
| 3 | 2 | p22 | 4.740 | 9 | 1.820 | −0.3091 | 0.2217 |
| 3 | 2 | p23 | 10.230 | 29 | 1.510 | 0.0862 | 0.5238 |
| 4 | 2 | p24 | 4.500 | 6 | 1.610 | 0.3593 | 0.7552 |
| 4 | 4 | p25 | 11.870 | 8 | 0.7500 | −0.2040 | −0.0692 |
| 4 | 3 | p26 | 6.140 | 9 | 2.300 | 0.1002 | 0.1600 |
| 5 | 3 | p27 | 7.210 | 7 | 0.5200 | 0.3560 | −0.2187 |
| 5 | 3 | p28 | 11.150 | 9 | 1.960 | 0.0284 | 0.0103 |
| 5 | 4 | p29 | 9.300 | 26 | 2.180 | −0.1032 | −0.1302 |
| 5 | 3 | p30 | 13.550 | 31 | 2.300 | −0.1258 | 0.0778 |
| 7 | 3 | p31 | 6.960 | 9 | 1.120 | 0.1835 | 0.0367 |
| 7 | 4 | p32 | 7.070 | 11 | 1.430 | 0.0758 | −0.2869 |
| 7 | 3 | p33 | 7.030 | 24 | 1.280 | 0.2297 | 0.2908 |
| 8 | 4 | p34 | 8.950 | 11 | 2.380 | 0.1095 | −0.0263 |
| 10 | 3 | p35 | 5.290 | 11 | 1.630 | 0.3588 | 0.0270 |
| 11 | 4 | p36 | 8.810 | 15 | 1.990 | −0.3356 | 0.0227 |
| 11 | — | — | — | 28 | 2.330 | — | — |
| 11 | — | — | — | 30 | 1.150 | — | — |
| 12 | — | — | — | 16 | 1.980 | — | — |
| 12 | — | — | — | 17 | 1.480 | — | — |
| 12 | — | — | — | 18 | 1.950 | — | — |
| 12 | — | — | — | 19 | 1.160 | — | — |
| 12 | — | — | — | 22 | 0.8900 | — | — |
| 12 | — | — | — | 23 | 0.7400 | — | — |
| 13 | — | — | — | 19 | 2.450 | — | — |
| 13 | — | — | — | 23 | 1.780 | — | — |
| 14 | — | — | — | 15 | 2.260 | — | — |
| 14 | — | — | — | 16 | 0.8700 | — | — |
| 14 | — | — | — | 18 | 1.010 | — | — |
| 14 | — | — | — | 19 | 2.470 | — | — |
| 14 | — | — | — | 20 | 2.440 | — | — |
| 14 | — | — | — | 22 | 2.250 | — | — |
| 14 | — | — | — | 23 | 0.6500 | — | — |
| 15 | — | — | — | 18 | 2.200 | — | — |
| 15 | — | — | — | 19 | 1.450 | — | — |
| 15 | — | — | — | 20 | 1.030 | — | — |
| 15 | — | — | — | 22 | 2.050 | — | — |
| 16 | — | — | — | 21 | 1.770 | — | — |
| 16 | — | — | — | 22 | 1.150 | — | — |
| 17 | — | — | — | 20 | 1.990 | — | — |
First 60 of 98 rows.
Nodes sorted by community: dense blocks on the diagonal are communities.
View data
| Column | Community | Node | Order | Row | Weight |
|---|---|---|---|---|---|
| 5 | 1 | p01 | 11 | 0 | 2.300 |
| 6 | 1 | p02 | 5 | 0 | 1.960 |
| 11 | 1 | p03 | 2 | 0 | 1.130 |
| 15 | 1 | p04 | 9 | 0 | 0.5200 |
| 32 | 1 | p05 | 1 | 0 | 1.040 |
| 2 | 1 | p06 | 4 | 1 | 1.820 |
| 3 | 1 | p07 | 0 | 1 | 1.610 |
| 4 | 1 | p08 | 3 | 1 | 2.390 |
| 5 | 1 | p09 | 6 | 1 | 1.920 |
| 9 | 1 | p10 | 7 | 1 | 0.8100 |
| 11 | 1 | p11 | 8 | 1 | 0.6900 |
| 5 | 1 | p12 | 10 | 2 | 0.9800 |
| 6 | 2 | p13 | 20 | 2 | 1.880 |
| 8 | 2 | p14 | 14 | 2 | 1.110 |
| 9 | 2 | p15 | 15 | 2 | 1.640 |
| 10 | 2 | p16 | 22 | 2 | 1.570 |
| 21 | 2 | p17 | 19 | 2 | 1.100 |
| 33 | 2 | p18 | 18 | 2 | 0.6900 |
| 35 | 2 | p19 | 12 | 2 | 0.7600 |
| 7 | 2 | p20 | 16 | 3 | 0.8200 |
| 8 | 2 | p21 | 21 | 3 | 0.5300 |
| 9 | 2 | p22 | 23 | 3 | 1.820 |
| 29 | 2 | p23 | 13 | 3 | 1.510 |
| 6 | 2 | p24 | 17 | 4 | 1.610 |
| 8 | 4 | p25 | 29 | 4 | 0.7500 |
| 9 | 3 | p26 | 27 | 4 | 2.300 |
| 7 | 3 | p27 | 26 | 5 | 0.5200 |
| 9 | 3 | p28 | 32 | 5 | 1.960 |
| 26 | 4 | p29 | 30 | 5 | 2.180 |
| 31 | 3 | p30 | 25 | 5 | 2.300 |
| 9 | 3 | p31 | 34 | 7 | 1.120 |
| 11 | 4 | p32 | 24 | 7 | 1.430 |
| 24 | 3 | p33 | 28 | 7 | 1.280 |
| 11 | 4 | p34 | 33 | 8 | 2.380 |
| 11 | 3 | p35 | 35 | 10 | 1.630 |
| 15 | 4 | p36 | 31 | 11 | 1.990 |
| 28 | — | — | — | 11 | 2.330 |
| 30 | — | — | — | 11 | 1.150 |
| 16 | — | — | — | 12 | 1.980 |
| 17 | — | — | — | 12 | 1.480 |
| 18 | — | — | — | 12 | 1.950 |
| 19 | — | — | — | 12 | 1.160 |
| 22 | — | — | — | 12 | 0.8900 |
| 23 | — | — | — | 12 | 0.7400 |
| 19 | — | — | — | 13 | 2.450 |
| 23 | — | — | — | 13 | 1.780 |
| 15 | — | — | — | 14 | 2.260 |
| 16 | — | — | — | 14 | 0.8700 |
| 18 | — | — | — | 14 | 1.010 |
| 19 | — | — | — | 14 | 2.470 |
| 20 | — | — | — | 14 | 2.440 |
| 22 | — | — | — | 14 | 2.250 |
| 23 | — | — | — | 14 | 0.6500 |
| 18 | — | — | — | 15 | 2.200 |
| 19 | — | — | — | 15 | 1.450 |
| 20 | — | — | — | 15 | 1.030 |
| 22 | — | — | — | 15 | 2.050 |
| 21 | — | — | — | 16 | 1.770 |
| 22 | — | — | — | 16 | 1.150 |
| 20 | — | — | — | 17 | 1.990 |
First 60 of 98 rows.
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
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 33.3% | 0.1789 | yes | p12, p06, p03 |
| 2 | 12 | 33.3% | 0.1584 | yes | p21, p15, p16 |
| 3 | 7 | 19.4% | 0.3752 | yes | p30, p28, p27 |
| 4 | 5 | 13.9% | 0.4935 | yes | p25, 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)
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
| Community | Nodes | Share | Conductance | In one piece | Best-connected nodes |
|---|---|---|---|---|---|
| 1 | 12 | 33.3% | 0.1789 | yes | p12, p06, p03 |
| 2 | 12 | 33.3% | 0.1584 | yes | p21, p15, p16 |
| 3 | 7 | 19.4% | 0.3752 | yes | p30, p28, p27 |
| 4 | 5 | 13.9% | 0.4935 | yes | p25, 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.
Correlation clustering: honor the judgments
ReadCorrelation 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, , 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.
Where each idea stands in CodeSplash
Read| Entry | In 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…Check your understanding
CheckpointCheck 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 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
: 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.
Do it on your own data
In the appLoad 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