TGraphX › Insights › Community Detection with TGraphX and NetworkX
← Back to Insights

Community Detection with TGraphX and NetworkX

Topic: Graph mining, generation, optimization and RL

Community detection asks a deceptively simple question: given a graph, which nodes naturally belong together? The question comes up in social networks, citation graphs, protein interaction networks and dependency maps, where a densely connected group often has an interpretable meaning.

This article states what TGraphX 1.5.1 provides, what it does not, and how to run and evaluate community detection by combining it with NetworkX and scikit-learn. TGraphX has label propagation and spectral clustering. It has no Louvain, Leiden or Girvan-Newman implementation and no partition-comparison scores such as NMI.

bash
pip install tgraphx networkx scikit-learn

NetworkX and scikit-learn are not TGraphX dependencies, so install them explicitly. Examples tested with TGraphX 1.5.1, NetworkX 3.7 and scikit-learn 1.9.1 on CPU.

Leiden needs a recent setup. NetworkX's own Leiden implementation requires NetworkX 3.7 or later, and NetworkX 3.7 requires Python 3.12 or later. NetworkX 3.6.1 raises NotImplementedError for leiden_communities (it can only hand the call to another backend), and 3.4.2 has no such function. The command above keeps an older NetworkX that is already installed (PyTorch itself depends on NetworkX); on Python 3.12 or later, pip install -U "networkx>=3.7" upgrades it. The other examples on this page also run on NetworkX 3.4.2 and 3.6.1.


What Community Detection Is Solving

A community is loosely defined as a set of nodes with more internal edges than you would expect by chance. The most common formal score is modularity (Newman and Girvan, 2004):

Q = (1 / 2m) * Σ_{ij} [ A_ij - k_i * k_j / (2m) ] * δ(c_i, c_j)

Here m is the number of undirected edges, A_ij is the adjacency matrix, k_i is the degree of node i, and δ(c_i, c_j) is 1 if nodes i and j are in the same community and 0 otherwise. The sum runs over all pairs of nodes in the same community, whether or not they are connected.

Q = 0 means the partition has as many internal edges as a random graph with the same degrees would have on average. Q stays below 1, and it can be negative. A value around 0.3 or higher is often quoted as a sign of community structure, but treat that as a rough heuristic: optimised partitions of purely random sparse graphs can reach such values too (Guimerà et al., 2004).

Community detection is unsupervised. No labels guide the optimisation, and the number of communities is usually not known in advance. That makes evaluation harder than for supervised classification.


Algorithm Families

Modularity optimisation (Louvain, Leiden) starts from single-node communities, moves nodes to increase Q, then merges communities into super-nodes and repeats. It scales well to large sparse graphs. Louvain can return badly connected or even disconnected communities, which Leiden was designed to prevent.

Divisive methods (Girvan-Newman) work in reverse: they repeatedly remove the edge with the highest edge betweenness, so bridges between groups disappear first. Betweenness has to be recomputed after every removal, which costs O(mn) each time on an unweighted graph and makes the method impractical beyond small graphs.

Spectral methods use eigenvectors of the graph Laplacian. The eigenvector of the second-smallest eigenvalue (the Fiedler vector) indicates how to cut the graph into two weakly connected parts, and spectral clustering runs k-means on a few such eigenvectors. You must choose the number of clusters. A dense eigendecomposition costs O(n³); sparse solvers that compute only a few eigenvectors are much cheaper.

Label propagation gives every node a unique label, then repeatedly sets each node's label to the most common label among its neighbours (Raghavan et al., 2007). It is nearly linear in the number of edges. In the original algorithm, node order and ties are random, so runs can differ.

Method Call You choose k Control randomness with
Louvain networkx.community.louvain_communities no seed=
Leiden (NetworkX 3.7+, Python 3.12+) networkx.community.leiden_communities no seed=
Girvan-Newman networkx.community.girvan_newman you pick the level not needed
Spectral clustering tgraphx.mining.spectral_clustering yes seed=
Label propagation, randomised networkx.community.asyn_lpa_communities no seed=
Label propagation, semi-synchronous networkx.community.label_propagation_communities no deterministic, no seed
Label propagation, in-order sweep tgraphx.mining.label_propagation_communities no deterministic, seed= has no effect

Setup: A Graph with a Known Split

TGraphX community functions take (edge_index, num_nodes), not a Graph object, and return a label vector with one community id per node. NetworkX returns lists of node sets. Two small converters bridge the formats.

python
import networkx as nx
import torch
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_mutual_info_score, normalized_mutual_info_score

from tgraphx import mining

# Zachary's karate club: 34 members, 78 friendships (listed in both directions).
edge_index, num_nodes = mining.karate_club_graph()
print(tuple(edge_index.shape), num_nodes)      # (2, 156) 34

def to_nx(edge_index, num_nodes):
    G = nx.Graph()
    G.add_nodes_from(range(num_nodes))
    G.add_edges_from(edge_index.t().tolist())
    return G

def to_sets(labels):
    """Label vector -> list of node sets (what NetworkX expects)."""
    return [set((labels == c).nonzero().flatten().tolist()) for c in labels.unique().tolist()]

def to_labels(communities, num_nodes):
    """List of node sets -> label vector."""
    labels = torch.empty(num_nodes, dtype=torch.long)
    for c, members in enumerate(communities):
        labels[list(members)] = c
    return labels

G = to_nx(edge_index, num_nodes)

# The split the club really made, recorded in NetworkX's copy of the dataset.
club = nx.karate_club_graph()
factions = torch.tensor([int(club.nodes[i]["club"] != "Mr. Hi") for i in range(num_nodes)])

The graph G is built without edge weights on purpose. NetworkX's own karate_club_graph() carries a weight attribute that louvain_communities would use by default.


Louvain and Girvan-Newman with NetworkX

python
for seed in range(5):
    comms = nx.community.louvain_communities(G, seed=seed)
    print(f"seed {seed}: {len(comms)} communities, Q = {nx.community.modularity(G, comms):.4f}")
# seed 0: 4 communities, Q = 0.4198
# seed 1: 4 communities, Q = 0.4188
# seed 2: 4 communities, Q = 0.4188
# seed 3: 4 communities, Q = 0.4151
# seed 4: 4 communities, Q = 0.4151

first_split = next(nx.community.girvan_newman(G))
print([len(c) for c in first_split],
      round(nx.community.modularity(G, first_split), 4))                     # [15, 19] 0.36

Louvain visits nodes in a random order, so different seeds give slightly different partitions. Fix the seed, and when conclusions depend on the exact grouping, run several seeds and report how much they vary. girvan_newman is a generator: each next call returns the next, finer split.

The highest-modularity partitions found here have four communities, while the club split into two. Neither is wrong; they answer different questions.

Leiden (NetworkX 3.7 or later)

The version check keeps the script usable on older releases and says why Leiden was left out:

python
nx_release = tuple(int(part) for part in nx.__version__.split(".")[:2])

if nx_release >= (3, 7):
    leiden = nx.community.leiden_communities(G, metric="modularity", seed=0)
    print(len(leiden), round(nx.community.modularity(G, leiden), 4))         # 4 0.4198
else:
    print(f"Leiden skipped: needs NetworkX 3.7+ (Python 3.12+), found {nx.__version__}")

Pass metric="modularity", because the default there is a different quality function (CPM).


Spectral Community Detection in TGraphX

mining.spectral_clustering embeds each node with num_clusters eigenvectors of the normalized Laplacian (skipping the first one) and then runs a single k-means from randomly chosen starting points. The seed matters:

python
for seed in range(5):
    labels = mining.spectral_clustering(edge_index, num_nodes, num_clusters=2, seed=seed)
    q = nx.community.modularity(G, to_sets(labels))
    ami = adjusted_mutual_info_score(factions, labels)
    print(f"seed {seed}: Q = {q:.3f}, AMI = {ami:.3f}")
# seed 0: Q = 0.304, AMI = 0.266
# seed 1: Q = 0.371, AMI = 0.833
# seed 2: Q = 0.304, AMI = 0.266
# seed 3: Q = 0.133, AMI = 0.181
# seed 4: Q = 0.371, AMI = 0.833

AMI measures agreement with the real two-way split (1 is identical, around 0 is chance level); it is explained below. A practical remedy that needs no labels is to run several seeds and keep the partition with the highest modularity:

python
candidates = [mining.spectral_clustering(edge_index, num_nodes, 2, seed=s) for s in range(10)]
best = max(candidates, key=lambda lab: nx.community.modularity(G, to_sets(lab)))
print(round(nx.community.modularity(G, to_sets(best)), 3),
      round(adjusted_mutual_info_score(factions, best), 3))      # 0.371 0.833

For two communities you can also split on the sign of the Fiedler vector, which involves no k-means at all:

python
fiedler, _ = mining.fiedler_vector(edge_index, num_nodes)
split = (fiedler > 0).long()
wrong = int((split != factions).sum())
print(min(wrong, num_nodes - wrong), "of", num_nodes, "members differ")   # 2 of 34

fiedler_vector uses the unnormalized Laplacian D - A. Because this edge_index lists both directions of every edge, TGraphX 1.5.1 counts each edge twice there: the eigenvector is unaffected, but the second return value (and mining.algebraic_connectivity) is twice the textbook value.

spectral_clustering builds dense matrices and raises an error above 500 nodes by default (max_nodes=500). Floating-point eigensolvers can differ slightly between platforms, so your exact numbers may differ from the comments. Community detection is not the only place where tgraphx.mining 1.5.1 needs checking: TGraphX vs NetworkX cross-checks other routines against NetworkX.


Label Propagation: Check What It Returns

TGraphX's label_propagation_communities visits nodes in index order, updates labels in place and gives every tie to the smallest label. That makes it deterministic (the seed argument has no effect), but small labels can spread across the whole graph:

python
lpa = mining.label_propagation_communities(edge_index, num_nodes)
print(lpa.unique().numel())        # 1: the whole karate club is one community

# Two 6-node cliques joined by a single edge.
clique = [(i, j) for i in range(6) for j in range(6) if i != j]
edges = clique + [(i + 6, j + 6) for i, j in clique] + [(0, 6), (6, 0)]
barbell = torch.tensor(edges).t()
print(mining.label_propagation_communities(barbell, 12).tolist())
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In the first sweep, the node at the far end of the bridge sees only distinct labels among its neighbours, so the tie goes to the label arriving over the bridge, and its clique follows. The result depends on how nodes are numbered. Always check how many communities came back before using them.

NetworkX's asynchronous label propagation breaks ties randomly and separates the two cliques:

python
parts = nx.community.asyn_lpa_communities(to_nx(barbell, 12), seed=0)
print([sorted(c) for c in parts])
# [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]

for seed in range(4):
    comms = list(nx.community.asyn_lpa_communities(G, seed=seed))
    print(f"seed {seed}: sizes {sorted(map(len, comms), reverse=True)}, "
          f"Q = {nx.community.modularity(G, comms):.3f}")
# seed 0: sizes [17, 12, 5], Q = 0.402
# seed 1: sizes [17, 13, 4], Q = 0.385
# seed 2: sizes [17, 17], Q = 0.372
# seed 3: sizes [29, 5], Q = 0.133

The spread across seeds on the karate club is large, so do not rely on a single run.

NetworkX also has a function called label_propagation_communities: the semi-synchronous method of Cordasco and Gargano (2010). It takes no k and no seed, and returns the same result every time for the same graph built in the same node order. It separates the two cliques:

python
semi = nx.community.label_propagation_communities(to_nx(barbell, 12))
print(sorted(sorted(c) for c in semi))
# [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]

reordered = nx.Graph(edge_index.t().tolist())      # same edges, nodes inserted in another order
for name, graph in [("nodes 0..33 in order", G), ("other node order", reordered)]:
    comms = list(nx.community.label_propagation_communities(graph))
    print(f"{name:20s} sizes {sorted(map(len, comms), reverse=True)}, "
          f"Q = {nx.community.modularity(graph, comms):.3f}")
# nodes 0..33 in order sizes [16, 15, 3], Q = 0.325
# other node order     sizes [29, 3, 2], Q = 0.112

Deterministic does not mean better, or independent of how the graph was built. Both karate results score below every Louvain run above, and changing only the order in which nodes were added turns sizes 16, 15 and 3 into 29, 3 and 2.

This unsupervised procedure is also different from semi-supervised label propagation, which spreads known class labels to unlabeled nodes.


Evaluating a Partition

Without ground truth, compare partitions of the same graph with modularity, and use networkx.community.modularity. Do not use tgraphx.mining.modularity (or the modularity field of mining.community_summary) in 1.5.1: it subtracts the degree term only for connected pairs. Putting all 34 members in one community should score 0:

python
one_community = torch.zeros(num_nodes, dtype=torch.long)
print(round(mining.modularity(edge_index, one_community, num_nodes), 4))   # 0.4017 (wrong)
print(nx.community.modularity(G, [set(range(num_nodes))]))                 # 0.0

A higher Q does not prove a better answer. Modularity has its own biases, described under limitations.

With ground truth, for example a synthetic graph with planted communities, compare label vectors. Community ids are arbitrary, so use a score that ignores renaming, not accuracy:

python
ei, n, truth = mining.planted_partition_graph(num_communities=3, community_size=30,
                                              p_in=0.3, p_out=0.01, seed=0)
P = to_nx(ei, n)
# The same three eigenvectors that spectral_clustering(ei, n, 3) computes internally.
embedding = mining.laplacian_eigvec_positional_encoding(ei, n, k=3)

results = {
    "Louvain (NetworkX)": to_labels(nx.community.louvain_communities(P, seed=0), n),
    "spectral_clustering, seed=0": mining.spectral_clustering(ei, n, 3, seed=0),
    "eigenvectors + KMeans(n_init=10)": torch.from_numpy(
        KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(embedding.numpy())),
    "mining.label_propagation (TGraphX)": mining.label_propagation_communities(ei, n),
}
for name, labels in results.items():
    q = nx.community.modularity(P, to_sets(labels))
    ami = adjusted_mutual_info_score(truth, labels)
    print(f"{name:35s} k={labels.unique().numel()}  Q={q:.3f}  AMI={ami:.3f}")
# Louvain (NetworkX)                  k=3  Q=0.590  AMI=1.000
# spectral_clustering, seed=0         k=3  Q=0.454  AMI=0.750
# eigenvectors + KMeans(n_init=10)    k=3  Q=0.590  AMI=1.000
# mining.label_propagation (TGraphX)  k=1  Q=0.000  AMI=0.000

This is one easy synthetic graph, not a ranking of the methods. The second and third rows start from the same eigenvectors, so only the k-means step differs: TGraphX runs it once from randomly chosen nodes, while scikit-learn uses k-means++ initialisation and ten restarts here. The latter recovers the planted groups; the single run with seed=0 does not, although some other seeds do.

Normalized Mutual Information (NMI) is the score you will see most often. It lies between 0 and 1, is symmetric and ignores label renaming, but it is not corrected for chance: unrelated labelings can score well above 0, especially with many clusters. Adjusted Mutual Information (AMI) subtracts the expected value for random labelings (Vinh et al., 2010).

python
gen = torch.Generator().manual_seed(0)
a = torch.randint(0, 10, (100,), generator=gen)
b = torch.randint(0, 10, (100,), generator=gen)      # independent of a
print(f"NMI = {normalized_mutual_info_score(a, b):.3f}")   # NMI = 0.183
print(f"AMI = {adjusted_mutual_info_score(a, b):.3f}")     # AMI = -0.038

Both scores assume each node belongs to exactly one community.


Using Community Structure as Graph Features

Detected communities can be fed into a GNN as extra node features, typically one-hot encoded:

python
import torch.nn.functional as F
from tgraphx import Graph

node_x = torch.randn(num_nodes, 16)            # stand-in for your node features
community = to_labels(nx.community.louvain_communities(G, seed=0), num_nodes)
onehot = F.one_hot(community).float()

graph = Graph(node_features=torch.cat([node_x, onehot], dim=1), edge_index=edge_index)
print(graph.feature_shape)                     # (20,)

Three cautions apply:

  • Community ids mean nothing outside this graph and this run. A model trained on them does not transfer to another graph.
  • If you evaluate link prediction, detect communities on the training edges only. Otherwise the test edges shape the features.
  • If you detect communities with class labels in view (for example by picking the seed that matches them best), restrict that choice to training nodes.

Limitations and Honest Notes

  • Resolution limit. Modularity optimisation can merge clearly separate modules when they are small relative to the whole graph: modules with a number of internal edges of the order of √(2m) or less are at risk (Fortunato and Barthélemy, 2007). NetworkX's resolution= argument above 1 favours smaller communities.
  • Randomness. Louvain, Leiden, randomised label propagation and k-means all depend on a seed. Report the seed and the variability. The deterministic label propagation functions take no usable seed, but their results can still change with node numbering or insertion order.
  • Weights. TGraphX's community functions take no edge weights. NetworkX's Louvain reads a weight edge attribute by default.
  • Direction. label_propagation_communities and spectral_clustering ignore edge direction. NetworkX's Louvain also accepts directed graphs.
  • Overlap. Every method above returns one community per node. For overlapping communities, NetworkX offers clique percolation (k_clique_communities).
  • Meaning. A high score does not make a community semantically meaningful. Inspect the members.

For the other mining tools in the package, see the graph mining overview. For scoring candidate edges, see the link prediction scoring guide.


Community Detection vs GNN-Based Approaches

Community detection uses structure only and needs no labels, so it suits exploration: finding cohesive groups in a new network and getting a grouping you can inspect. A GNN learns a target you define from labelled examples and can use node features, so it suits prediction. Neither is better in general, and a found community need not match any class you care about. See graph mining versus GNN message passing for the broader decision.

Community detection does not need meaningful node features. If you go on to train a GNN, they matter again; the shape-aware validation guide covers feature checks before training. For the mathematics behind the spectral method, see the graph spectral analysis article.


Frequently Asked Questions

How many communities does Louvain find? Whatever maximises its objective on your graph; you cannot request a number directly. Use resolution= to push towards larger or smaller communities. If you need exactly k, spectral clustering takes the number of clusters, but do not rely on a single run of TGraphX's version: run several seeds, compare the partitions as above and check the result.

Does TGraphX have Louvain? No. tgraphx.mining 1.5.1 implements none of Louvain, Leiden or Girvan-Newman. Use NetworkX or a dedicated library.

Is the Fiedler vector available? Yes: mining.fiedler_vector(edge_index, num_nodes) returns the vector and the second-smallest eigenvalue of D - A (see the doubling note above).

Louvain or label propagation? Both are heuristics. Label propagation is the simpler, rougher estimate; Louvain optimises an explicit objective. For reproducible runs, fix the seed of louvain_communities and asyn_lpa_communities. Two label propagation functions are deterministic and need no seed: networkx.community.label_propagation_communities and tgraphx.mining.label_propagation_communities. Check the number and sizes of the communities they return, because deterministic does not mean good (TGraphX's version collapses the karate club into one).


References

  • Zachary (1977). An information flow model for conflict and fission in small groups. Journal of Anthropological Research.
  • Girvan and Newman (2002). Community structure in social and biological networks. PNAS.
  • Newman and Girvan (2004). Finding and evaluating community structure in networks. Physical Review E.
  • Guimerà, Sales-Pardo and Amaral (2004). Modularity from fluctuations in random graphs and complex networks. Physical Review E.
  • Fortunato and Barthélemy (2007). Resolution limit in community detection. PNAS.
  • Raghavan, Albert and Kumara (2007). Near linear time algorithm to detect community structures in large-scale networks. Physical Review E.
  • von Luxburg (2007). A tutorial on spectral clustering. Statistics and Computing.
  • Blondel, Guillaume, Lambiotte and Lefebvre (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics.
  • Vinh, Epps and Bailey (2010). Information theoretic measures for clusterings comparison. Journal of Machine Learning Research.
  • Cordasco and Gargano (2010). Community detection via semi-synchronous label propagation algorithms. IEEE International Workshop on Business Applications of Social Network Analysis.
  • Traag, Waltman and van Eck (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports.