Static graphs
Generate graphs from the degree-corrected stochastic block model, load real networks and detect their communities.
The degree-corrected stochastic block model
CoDeBetHe generates graphs with communities from the degree-corrected stochastic block model (DC-SBM). Let $\mathcal{G}$ be a graph with $n$ nodes and $k$ communities, with label vector $\ell \in \{1,\dots,k\}^n$ and adjacency matrix $A \in \{0,1\}^{n\times n}$, where $A_{ij}=1$ if and only if $(ij)$ is an edge. The edges are drawn independently with probability
- The vector $\theta \in \mathbb{R}^n$, with $\frac{1}{n}\sum_i\theta_i = 1$, sets the expected degree of each node, so it can reproduce any degree distribution.
- The matrix $C\in\mathbb{R}^{k\times k}$ contains the affinity $C_{ab}$ between communities $a$ and $b$.
- The vector $\pi \in \mathbb{R}^k$ contains the fraction of nodes in each community, with $\sum_a \pi_a = 1$.

Create a synthetic graph
First, choose the size of the graph, the degree distribution and the size of the communities. For a homogeneous degree distribution (the classical stochastic block model), simply set $\theta_i = 1$ for every node.
import numpy as np
from codebethe import matrix_C, create_label_vector, adjacency_matrix_DCSBM
n = 10_000 # number of nodes
k = 10 # number of communities
# vector θ: here a power-law degree distribution
θ = np.random.uniform(3, 10, n) ** 3.5
θ = θ / θ.mean() # normalization: do not change
# vector π: community sizes, drawn around 1/k
π_v = np.abs(np.random.normal(1 / k, 1 / (2 * k), k))
π_v = π_v / π_v.sum() # normalization: do not change
using CoDeBetHe
using Distributions, DelimitedFiles, LinearAlgebra, DataFrames, StatsBase
n = floor(Int64, 10^4) # number of nodes
k = 10 # number of communities
# vector θ: here a power-law degree distribution
θ = rand(Uniform(3, 10), n).^3.5
θ = θ./mean(θ) # normalization: do not change
# vector π: community sizes, drawn around 1/k
π_v = abs.(rand(Normal(1/k, 1/(2*k)), k))
π_v = π_v/sum(π_v) # normalization: do not change
Then create the affinity matrix $C$ with matrix_C. It is built so that every row of $C\,{\rm diag}(\pi)$ sums to $c$, the expected average degree: the expected degree is then the same in every community, so the communities cannot be found just by looking at the degrees. The parameter f adds randomness to the off-diagonal elements, whose average is c_out. Set f = 0 to make them all equal.
c = 10. # average degree
c_out = 2. # average value of the off-diagonal terms
f = 2 / k # fluctuation of the off-diagonal terms
C = matrix_C(c_out, c, f, π_v)
ℓ = create_label_vector(n, k, π_v) # ground-truth labels (0, ..., k-1)
A = adjacency_matrix_DCSBM(C, c, ℓ, θ) # scipy.sparse adjacency matrix
c = 10. # average degree
c_out = 2. # average value of the off-diagonal terms
f = 2/k # fluctuation of the off-diagonal terms
C = matrix_C(c_out, c, f, π_v)
ℓ = create_label_vector(n, k, π_v) # ground-truth labels (1, ..., k)
A = adjacency_matrix_DCSBM(C, c, ℓ, θ) # sparse adjacency matrix
The adjacency matrix is stored in sparse format. Converting it to a dense matrix would drastically increase the computational cost.
Load a real graph
The datasets folder of the repository contains datasets.zip with several real networks: karate, dolphins, polbooks, football, email, polblogs, tv, fb, power, politicians, Gnutella, vip. Unzip it, then load an edge list and build the sparse adjacency matrix:
import numpy as np
from scipy.sparse import csr_matrix
el = np.loadtxt('datasets/polblogs.txt').astype(int) # edge list
if el.min() == 1: # node ids start from 0 in Python
el = el - 1
edges = np.vstack([el, el[:, ::-1]]) # symmetrize: (i, j) and (j, i)
n = len(np.unique(edges))
A = csr_matrix((np.ones(len(edges)), (edges[:, 0], edges[:, 1])), shape=(n, n))
using SparseArrays
el = convert(Array{Int64}, readdlm("datasets/polblogs.txt")) # edge list
if minimum(el) == 0 # node ids start from 1 in Julia
el = el .+ 1
end
fs = vcat(el[:,1], el[:,2]) # symmetrize: (i, j) and (j, i)
ss = vcat(el[:,2], el[:,1])
n = length(unique(vcat(fs, ss)))
A = sparse(fs, ss, ones(length(fs)), n, n)
If you use these datasets, please cite their authors. Karate: W. W. Zachary, J. Anthropol. Res. 33(4), 1977. Dolphins: D. Lusseau et al., Behav. Ecol. Sociobiol. 54(4), 2003. Polbooks: orgnet.com. Football: M. Girvan and M. E. J. Newman, PNAS 99(12), 2002. Polblogs: L. A. Adamic and N. Glance, LinkKDD 2005. All other datasets come from the SNAP collection (J. Leskovec and A. Krevl, 2014).
Detect the communities
community_detection_optimal_BH (or community_detection in Python) implements Algorithm 2 of our JMLR paper. If the number of communities k is not given, it is estimated. On the Political Blogs network, with k = 2:
from codebethe import community_detection
res = community_detection(A, k=2, verbose=1) # verbose: 0, 1 or 2
print(f"The modularity obtained is: mod = {res.modularity}")
o Largest eigenvalue of the non-backtracking matrix: ρ = 72.5596 Estimating ζ_2 found ζ_2 = 1.134 The modularity obtained is: mod = 0.4253096108332699
cluster = community_detection_optimal_BH(A; k = 2, verbose = 1) # verbose: 0, 1 or 2
printstyled("\nThe modularity obtained is: mod = ", cluster.modularity; color = 9)
o Computing the largest eigenvalue of the non-backtracking matrix : found ρ = 72.55957935536169. o Estimating the parameters ζ and their corresponding informative eigenvectors: Estimating ζ_2: found ζ_2 = 1.134. The residual of the associated eigenvector is 0.0002 o Running k-means Done The modularity obtained is: mod = 0.4253096108332699
The result contains the estimated labels ℓ, the number of communities k, the modularity of the partition and the values ζ of the Bethe-Hessian parameters. If you pass the ground-truth labels (ℓ = ...), it also contains the overlap with the ground truth. See the API reference for all options.