Communities, modularity and the stochastic block model
Study community detection through modularity, its resolution limit, Louvain and Leiden, stochastic block models and spectral methods near the detectability threshold.
After this lesson you can
- Define modularity relative to the configuration model and explain its resolution limit.
- Implement Louvain local moves and explain the issue addressed by Leiden.
- Generate stochastic block models and state the two-group Kesten-Stigum threshold.
- Compare adjacency, normalized Laplacian and Bethe Hessian spectral methods near the threshold.
- Evaluate partitions using NMI and ARI and interpret high modularity cautiously.
Before you start
What makes a group a community?
A monorepo can contain modules that mainly call one another; a transaction network can group accounts by shared activity. A partition that maximizes a number offers a hypothesis about structure, not proof of coordination or causation. We need a reference model, an algorithm and a way to check what it recovers when ground truth is known.
Assume an undirected, loop-free graph with edges for this first derivation. The configuration model preserves expected degrees by pairing endpoints at random: the term approximates the expected number of connections between and . Modularity compares observed connections with that null:
counts internal edges of once, , and controls resolution. At this is standard modularity. The sum over counts each undirected edge twice; distinguish from volume . The null is a statistical reference, not a perfect conditional distribution for all constraints of a simple graph. Even a random graph can have a partition with positive modularity: searching many partitions introduces optimism.
The matrix in parentheses is the modularity matrix . A positive entry indicates more observed weight than expected under the null for that pair; the objective sums these deviations only within communities. In particular, a high-degree node contributes more to the expected term than a low-degree node. If all nodes are in one community, ; this checks signs but does not prove that a positive partition is significant. To assess whether a value is surprising, compare appropriate null graphs and repeat the search on each null.
Move and contract
The first phase of Louvain and Leiden starts with one community per node. To move , first remove it from its previous community. If is the weight of edges from to a candidate community , its total degree after removal, and has no self-loop, inserting it in changes the contribution dependent on by
For the net gain of the move, subtract the same expression for reinsertion in the source community. Comparing insertion with zero alone ignores what was lost on removal. Accumulate by scanning neighbors and maintain community totals, so evaluating candidates costs plus managing those totals. Repeat until no permitted move improves . Then contract each community into a supernode; internal edges become self-loops of corresponding weight. Apply the phase again to the aggregated graph. Ordering and ties can change the partition: this is a heuristic, not a global-optimum guarantee.
If denotes the source community after removing , the explicit destination-minus-source difference is . Terms depending only on cancel. In an aggregated graph the self-loop accompanies the supernode in any move and also cancels in the comparison, although it still counts toward its degree. An implementation must preserve that convention when contracting: if it stores each internal edge twice on the diagonal of a symmetric matrix, row sums preserve the original volume.
A community can become disconnected if the node joining two parts moves to another community. Once contracted into one supernode, Louvain cannot split it at that level. Traag, Waltman and van Eck introduce Leiden with refinement before aggregation and prove connectivity guarantees under their procedure. Splitting disconnected components is a useful diagnostic, but does not implement all of Leiden’s decisions or guarantees.
The resolution limit
Consider cliques of nodes arranged in a ring, with even and one edge between consecutive cliques. Each clique has internal edges and . For the partition keeping each clique separate,
If adjacent cliques are merged in pairs, half the inter-clique edges become internal and each pair has twice the volume:
When this difference is positive, the natural clique partition does not maximize : one particular paired partition is better. This argument does not claim that pairs are globally optimal. For fixed and , increasing can cause merging even though local internal structure does not change.
The stochastic block model
The stochastic block model (SBM) assigns a latent label and generates independent edges with probability . In the symmetric sparse case with two equal groups, and , with fixed as grows. Each node has expected degree approximately ; and are not the expected internal and external degrees separately, which are approximately and .
For a simple matrix and fixed assignment, likelihood is the product of over edges and over non-edges. Its logarithm sums both terms. The degree-corrected SBM multiplies each pair’s intensity by node factors ; specify a normalization to identify and state how probabilities remain in . In the lab we use normalized positive factors and truncate probabilities above 1. Correction represents degree heterogeneity but does not automatically capture overlap, attributes or temporality of a real network.
If , the edge distribution does not depend on latent labels: the graph has no community signal. When , a neighbor is more likely to share a label than change it, but an individual edge remains uncertain. Labels are exchangeable: a prediction swapping the names of both blocks is equally good. This model offers a test bed for controlling homophily and mean degree in a GNN, but one synthetic configuration cannot replace evaluation on real data and different splits.
Detectability and sparse spectra
For the symmetric two-group SBM in the sparse limit, the Kesten-Stigum threshold for weak recovery is
Above it, an algorithm asymptotically recovers a fraction better than chance after allowing global label exchange; below it, positive correlation cannot be obtained in this model. The result concerns weak recovery, not exact recovery of every node, and is not a promise for a finite sample. The criterion relates connection differences to noise in the local tree. Belief-propagation intuition views a signal that attenuates along an edge while competing with branching. Abbe’s survey distinguishes weak, partial and exact recovery and their assumptions.
This intuition can be expressed with two quantities: mean offspring count and label correlation across an edge . The product compares amplification by branches with squared signal loss; is exactly equivalent to the inequality above. This explains the mechanism rather than proving impossibility or giving a criterion valid for arbitrary degree distributions. Equality requires care and is not presented as guaranteed recovery.
The figure computes approximations with 60 Lanczos steps and flags absolute residuals above 0.01 as insufficient convergence. That threshold is a practical alert, not a universal classification guarantee: a repeated or nearly repeated eigenvalue can make the chosen sign vector depend on the basis even with a small residual. Isolated nodes and disconnected components can also create ties. Reliable analysis requires examining the spectrum, increasing precision and repeating seeds; the lab uses an independent solver for a second comparison.
Leading eigenvectors of can concentrate on a few high-degree nodes without representing the partition. The normalized Laplacian changes degree influence, but isolates and fluctuations still matter. The non-backtracking matrix and Bethe Hessian incorporate a different geometry. The former operates on directed edges and forbids immediately returning along the same edge. A lower-dimensional symmetric form is
For this assortative SBM we use and examine the second-smallest eigenvector. The Hessian does not automatically turn every real graph into an SBM: size, choice of , degree and eigenvector convergence affect the result. Saade, Krzakala and Zdeborová relate this operator to non-backtracking and study its performance on sparse models.
Lab: Louvain and blocks from scratch
A two-group balanced SBM is built with pairwise probabilities and no self-loops. When degree correction is enabled, factors are normalized by group and each probability is capped at 1; the generated matrix does not impose exact degrees. The modularity function supports weights and a diagonal representing twice the loop weight after contraction. Each move evaluates gains by scanning row entries and maintains each community’s total. Original labels are carried between levels. Mutual-information normalization here uses the arithmetic mean of entropies; a partition’s NMI does not prove that labels exist in a real graph.
import numpy as np
import networkx as nx
from scipy import sparse
from scipy.sparse.linalg import eigsh
def sbm(n,a,b,seed,degree_corrected=False):
assert n%2==0 and a>=b>=0
rng=np.random.default_rng(seed); labels=np.arange(n)//(n//2)
theta=rng.lognormal(mean=0,sigma=.4,size=n) if degree_corrected else np.ones(n)
for group in (0,1): theta[labels==group]/=theta[labels==group].mean()
base=np.where(labels[:,None]==labels[None,:],a,b)/n
probability=np.minimum(base*theta[:,None]*theta[None,:],1.)
mask=np.triu(rng.random((n,n))<probability,1)
A=sparse.csr_matrix((mask|mask.T).astype(float))
return A,labels
def modularity_matrix(A,labels,gamma=1.):
A=sparse.csr_matrix(A); labels=np.asarray(labels)
degree=np.asarray(A.sum(axis=1)).ravel(); twom=degree.sum()
if twom==0: return 0.
coo=A.tocoo()
inside=coo.data[labels[coo.row]==labels[coo.col]].sum()/twom
totals=np.bincount(labels,weights=degree)
return float(inside-gamma*np.sum((totals/twom)**2))
def local_move(A,gamma=1.,seed=0):
A=sparse.csr_matrix(A); n=A.shape[0]
degree=np.asarray(A.sum(axis=1)).ravel(); m=degree.sum()/2
labels=np.arange(n); totals=degree.copy(); rng=np.random.default_rng(seed)
if m==0: return labels
while True:
changed=False
for i in rng.permutation(n):
old=labels[i]; start,end=A.indptr[i:i+2]
neighbors=A.indices[start:end]; weights=A.data[start:end]
kin={}
for j,w in zip(neighbors,weights):
if j!=i: kin[labels[j]]=kin.get(labels[j],0.)+w
totals[old]-=degree[i]
old_score=kin.get(old,0.)/m-gamma*degree[i]*totals[old]/(2*m*m)
best=old; best_gain=0.
for c in kin:
score=kin[c]/m-gamma*degree[i]*totals[c]/(2*m*m)
if score-old_score>best_gain+1e-12:
best=c; best_gain=score-old_score
labels[i]=best; totals[best]+=degree[i]
changed |= best!=old
if not changed: break
_,labels=np.unique(labels,return_inverse=True)
return labels
def louvain(A,gamma=1.,seed=0):
current=sparse.csr_matrix(A,dtype=float); mapping=np.arange(current.shape[0]); history=[]
for level in range(30):
labels=local_move(current,gamma,seed+level)
mapping=labels[mapping]
_,mapping=np.unique(mapping,return_inverse=True)
history.append(modularity_matrix(A,mapping,gamma))
communities=int(labels.max())+1
if communities==current.shape[0]: break
membership=sparse.csr_matrix((np.ones(len(labels)),(np.arange(len(labels)),labels)),shape=(len(labels),communities))
current=(membership.T@current@membership).tocsr()
return mapping,history
def nmi(truth,pred):
_,x=np.unique(truth,return_inverse=True); _,y=np.unique(pred,return_inverse=True)
table=np.zeros((x.max()+1,y.max()+1)); np.add.at(table,(x,y),1)
table/=len(x); px=table.sum(axis=1); py=table.sum(axis=0)
mask=table>0; expected=px[:,None]*py[None,:]
mutual=np.sum(table[mask]*np.log(table[mask]/expected[mask]))
hx=-np.sum(px[px>0]*np.log(px[px>0])); hy=-np.sum(py[py>0]*np.log(py[py>0]))
return float(2*mutual/(hx+hy)) if hx+hy>0 else 1.
def ari(truth,pred):
_,x=np.unique(truth,return_inverse=True); _,y=np.unique(pred,return_inverse=True)
table=np.zeros((x.max()+1,y.max()+1),dtype=np.int64); np.add.at(table,(x,y),1)
pairs=lambda z: np.sum(z*(z-1)/2)
total=len(x)*(len(x)-1)/2
if total==0: return 1.
observed=pairs(table); rows=pairs(table.sum(axis=1)); cols=pairs(table.sum(axis=0))
expected=rows*cols/total; denominator=(rows+cols)/2-expected
return float((observed-expected)/denominator) if denominator else 1.
def as_partition(labels):
return [set(np.flatnonzero(labels==c)) for c in np.unique(labels)]Compare calculated modularity with NetworkX on the same partition, and run its Louvain implementation with the same seed. Visit orders and ties can differ, so neither nor the partitions need match. The list of modularities by level should be nondecreasing. The sweep uses three seeds per point and shows each NMI; these are not confidence intervals.
NMI measures information shared between partition and truth, normalized by their entropies; it is 1 when they agree up to renaming. The adjusted Rand index (ARI) compares node pairs in the same or different groups and corrects for expected agreement under a fixed-size partition model. It can be negative and is 1 for perfect agreement. Both use synthetic truth: they cannot directly evaluate unknown communities in a real network and need not rank two partitions identically.
for seed in range(3):
A,truth=sbm(240,10,2,seed,degree_corrected=True)
found,history=louvain(A,seed=seed)
G=nx.from_scipy_sparse_array(A)
value=nx.community.modularity(G,as_partition(found))
assert np.isclose(value,modularity_matrix(A,found))
assert np.all(np.diff(history)>-1e-10)
reference=nx.community.louvain_communities(G,seed=seed)
ref=np.zeros(len(truth),int)
for i,group in enumerate(reference): ref[list(group)]=i
print('semilla',seed,'niveles',len(history),'Q propio/NX',round(value,4),round(nx.community.modularity(G,reference),4),
'NMI propio/NX',round(nmi(truth,found),4),round(nmi(truth,ref),4),
'ARI propio/NX',round(ari(truth,found),4),round(ari(truth,ref),4))
for b in (1,3,5,7):
values=[]
for seed in (20,21,22):
A,truth=sbm(240,8,b,seed,degree_corrected=True)
labels,_=louvain(A,seed=seed)
values.append(nmi(truth,labels))
print('a-b',8-b,'NMI medio',round(float(np.mean(values)),3),'semillas',np.round(values,3).tolist())Lab: spectra near the threshold
In a 600-node SBM without degree correction, calculate the second-largest eigenvector of adjacency and normalized adjacency, and the second-smallest of the Bethe Hessian. Signs are evaluated after allowing a global label swap. Accuracy is an external measure using synthetic truth only for evaluation; it must not select a method on an unlabeled set. The mean and range of three seeds per point are shown, not a precise population estimate. Isolated nodes receive zero normalization.
def signs(vector,truth):
x=(vector>=0).astype(int); accuracy=np.mean(x==truth)
return max(accuracy,1-accuracy)
def spectra(A,truth):
n=A.shape[0]; degree=np.asarray(A.sum(axis=1)).ravel(); mean=degree.mean()
inv=np.divide(1.,np.sqrt(degree),out=np.zeros_like(degree),where=degree>0)
normalized=sparse.diags(inv)@A@sparse.diags(inv)
r=np.sqrt(mean); H=sparse.diags((r*r-1)+degree)-r*A
initial=np.random.default_rng(123).normal(size=n)
_,u=eigsh(A,k=2,which='LA',v0=initial)
_,v=eigsh(normalized,k=2,which='LA',v0=initial)
_,w=eigsh(H,k=2,which='SA',v0=initial)
return [signs(u[:,-2],truth),signs(v[:,-2],truth),signs(w[:,1],truth)]
for b in (1,3,5,7):
rows=[]
for seed in (10,11,12):
A,truth=sbm(600,8,b,seed)
rows.append(spectra(A,truth))
print('b',b,'señal KS',(8-b)**2-2*(8+b),'exactitud media A/norm/Bethe',np.round(np.mean(rows,axis=0),3).tolist(),
'intervalo de cada método',np.round(np.ptp(rows,axis=0),3).tolist())Local comparison with Leiden
The next cell uses a separate local runtime with python-igraph, leidenalg, NetworkX and scikit-learn installed. It generates its own SBM, compares NetworkX Louvain with Leiden for resolution-1 modularity and counts communities whose induced subgraph is disconnected. This checks these three realizations rather than estimating general frequency or proving Leiden’s guarantees. Quality is evaluated against synthetic truth and is not used to select seeds.
import numpy as np
import networkx as nx
import igraph as ig
import leidenalg as la
from sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score
def local_sbm(n,a,b,seed):
rng=np.random.default_rng(seed); truth=np.arange(n)//(n//2)
prob=np.where(truth[:,None]==truth[None,:],a,b)/n
upper=np.triu(rng.random((n,n))<prob,1)
u,v=np.nonzero(upper)
return list(zip(u.tolist(),v.tolist())),truth
for seed in (30,31,32):
edges,truth=local_sbm(300,8,3,seed)
G=nx.Graph(); G.add_nodes_from(range(len(truth))); G.add_edges_from(edges)
igraph=ig.Graph(n=len(truth),edges=edges,directed=False)
lou=nx.community.louvain_communities(G,seed=seed)
lei=la.find_partition(igraph,la.RBConfigurationVertexPartition,resolution_parameter=1.,seed=seed)
leiden_groups=[set(group) for group in lei]
def measure(groups):
pred=np.zeros(len(truth),dtype=int)
for i,group in enumerate(groups): pred[list(group)]=i
disconnected=sum(not nx.is_connected(G.subgraph(group)) for group in groups)
return {'Q':round(nx.community.modularity(G,groups),4),
'NMI':round(normalized_mutual_info_score(truth,pred),4),
'ARI':round(adjusted_rand_score(truth,pred),4),
'desconectadas':disconnected}
print('semilla',seed,'Louvain',measure(lou),'Leiden',measure(leiden_groups))npm run lab and open the connection link.In the local execution for these three seeds, Leiden obtained modularities between 0.4365 and 0.4507 and neither output contained disconnected communities. For seed 30, however, its NMI was 0.0531 versus Louvain’s 0.0857 despite higher . This particular comparison reminds us that optimizing modularity and recovering the latent partition are different goals; it does not establish which method generally wins.
Exercises
Step 1 of 2. How much does the internal-edge contribution change?
import numpy as np
def modularity(edge_index, communities):
passKey ideas
The SBM allows algorithms to be checked against known truth. In the sparse regime, the weak-recovery threshold and eigenvector localization explain why an apparent visual separation is insufficient to guarantee that a partition is recoverable.