Module contents
Lesson 5 of 30Core 100 min

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 m>0m>0 edges for this first derivation. The configuration model preserves expected degrees by pairing endpoints at random: the term kikj/(2m)k_i k_j/(2m) approximates the expected number of connections between ii and jj. Modularity compares observed connections with that null:

Qγ=12m∑ij(Aij−γkikj2m)1[ci=cj]=∑C(mCm−γ(KC2m)2).Q_\gamma=\frac1{2m}\sum_{ij}\left(A_{ij}-\gamma\frac{k_i k_j}{2m}\right)\mathbf 1[c_i=c_j] =\sum_C\left(\frac{m_C}{m}-\gamma\left(\frac{K_C}{2m}\right)^2\right).

mCm_C counts internal edges of CC once, KC=∑i∈CkiK_C=\sum_{i\in C}k_i, and γ>0\gamma>0 controls resolution. At γ=1\gamma=1 this is standard modularity. The sum over i,ji,j counts each undirected edge twice; distinguish mCm_C from volume KCK_C. 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 B=A−γkk⊤/(2m)B=A-\gamma kk\T/(2m). 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, Q1=0Q_1=0; 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 ii, first remove it from its previous community. If ki,Ck_{i,C} is the weight of edges from ii to a candidate community CC, KCK_C its total degree after removal, and ii has no self-loop, inserting it in CC changes the contribution dependent on CC by

ΔQinsert(i,C)=ki,Cm−γkiKC2m2.\Delta Q_{\mathrm{insert}}(i,C)=\frac{k_{i,C}}{m}-\gamma\frac{k_iK_C}{2m^2}.

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 ki,Ck_{i,C} by scanning neighbors and maintain community totals, so evaluating candidates costs O(ki)O(k_i) plus managing those totals. Repeat until no permitted move improves QQ. 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 AA denotes the source community after removing ii, the explicit destination-minus-source difference is (ki,C−ki,A)/m−γki(KC−KA)/(2m2)(k_{i,C}-k_{i,A})/m-\gamma k_i(K_C-K_A)/(2m^2). Terms depending only on ki2k_i^2 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.

InteractiveLocal moves and contraction

Fixed synthetic network of 60 nodes; colors are reused for more than eight communities.

Modularity Q−0.0189
Communities60
Next node1
Proposed gain0.00845
Fixed synthetic network of 60 nodes. The highlighted node is evaluated using actual modularity gain and edges are grouped on contraction. The hinge example uses an explicit intermediate partition to show how a local improvement can disconnect a community; splitting its components illustrates a connectivity condition and does not reproduce all of Leiden.

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 cc cliques of ss nodes arranged in a ring, with even cc and one edge between consecutive cliques. Each clique has ℓ=s(s−1)/2\ell=s(s-1)/2 internal edges and m=c(ℓ+1)m=c(\ell+1). For the partition keeping each clique separate,

Qsep=cℓm−γc.Q_{\mathrm{sep}}=\frac{c\ell}{m}-\frac\gamma c.

If adjacent cliques are merged in pairs, half the inter-clique edges become internal and each pair has twice the volume:

Qpar−Qsep=c2m−γc.Q_{\mathrm{par}}-Q_{\mathrm{sep}}=\frac{c}{2m}-\frac\gamma c.

When this difference is positive, the natural clique partition does not maximize QγQ_\gamma: one particular paired partition is better. This argument does not claim that pairs are globally optimal. For fixed ss and γ\gamma, increasing cc can cause merging even though local internal structure does not change.

InteractiveCliques and resolution
12 cliques of 4

Los colores alternos identifican vecinas; la partición por pares agrupa cada clique par con la siguiente. Hay 84 aristas en total.

12
4
1.0
Q: separate cliques0.7738
Q: adjacent pairs0.7619
Better of the twoseparate
A ring of cliques represented by circles. The individual-clique partition and consecutive-pair partition are compared exactly; other partitions may have greater modularity.

The stochastic block model

The stochastic block model (SBM) assigns a latent label zi∈{1,…,K}z_i\in\{1,\ldots,K\} and generates independent edges with probability BzizjB_{z_i z_j}. In the symmetric sparse case with two equal groups, pin=a/np_{\rm in}=a/n and pout=b/np_{\rm out}=b/n, with a>b≥0a>b\ge0 fixed as nn grows. Each node has expected degree approximately (a+b)/2(a+b)/2; aa and bb are not the expected internal and external degrees separately, which are approximately a/2a/2 and b/2b/2.

For a simple matrix and fixed assignment, likelihood is the product of BzizjB_{z_i z_j} over edges and 1−Bzizj1-B_{z_i z_j} over non-edges. Its logarithm sums both terms. The degree-corrected SBM multiplies each pair’s intensity by node factors θiθj\theta_i\theta_j; specify a normalization to identify θ\theta and state how probabilities remain in [0,1][0,1]. 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 a=ba=b, the edge distribution does not depend on latent labels: the graph has no community signal. When a>ba>b, 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

(a−b)2>2(a+b).(a-b)^2>2(a+b).

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 d=(a+b)/2d=(a+b)/2 and label correlation across an edge η=(a−b)/(a+b)\eta=(a-b)/(a+b). The product dη2d\eta^2 compares amplification by branches with squared signal loss; dη2>1d\eta^2>1 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.

InteractiveAn SBM realization
48120510abcurve: (a − b)² = 2(a + b)
8
2
12345
KS signal16
Observed mean degreenot run
Each run actually generates 2000 nodes with probabilities a/n and b/n, a seed and three operators. The plane shows the asymptotic boundary; finite accuracies are compared after swapping labels and Ritz residuals measure numerical convergence. Seeds are not averaged and no realization's result is guaranteed.

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

H(r)=(r2−1)I−rA+D.\mat H(r)=(r^2-1)\mat I-r\mat A+\mat D.

For this assortative SBM we use r=dˉr=\sqrt{\bar d} and examine the second-smallest eigenvector. The Hessian does not automatically turn every real graph into an SBM: size, choice of rr, 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.

[ ]SBM and Louvain from scratchBrowser
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 QQ 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.

[ ]Louvain comparison and sweepBrowser
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.

[ ]Adjacency, normalization and BetheBrowser
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)@[email protected](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.

[ ]Louvain versus LeidenLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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 QQ. 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

Proof
Prove: Derive the contribution of inserting a node removed from its community into community C.
0
The undirected graph has no self-loops; m is the total number of edges and K_C is measured before insertion.

Step 1 of 2. How much does the internal-edge contribution change?

Numeric
For the symmetric assortative SBM with a = 5, calculate the critical b in 0 ≤ b < 5 where (a − b)² = 2(a + b).
Quiz
Why can adjacency spectral methods fail on a sparse graph with a few hubs?
Quiz
What does the Kesten-Stigum threshold guarantee in the sparse symmetric two-group SBM?
Code
Implement modularity(edge_index, communities). edge_index has shape (2,m) and contains each undirected loop-free edge exactly once; communities has an integer label per node, including isolates. For m=0 return 0. Calculate Q with gamma=1 in O(n+m).
import numpy as np
def modularity(edge_index, communities):
  pass
Shift+Enter to run

Key ideas

Key idea
Modularity compares internal edges with a degree-based null, and its resolution depends on global scale. Louvain seeks local improvements; Leiden adds refinement before contraction.

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.