Contents
Figure 1: NetworkX for Machine Learning: Centrality, Communities, and Graph Features - every cable in this rack is an edge, and every measure below is just a different question asked about those edges
You have a graph and a scikit-learn pipeline, and no GPU. No PyTorch Geometric, no CUDA, no GNN. Can you still use the structure? Yes - NetworkX turns "who connects to whom" into ordinary table columns, and a random forest will consume them without complaint.
But the usual version of this advice has a hole in it, and I found it while running the code below. The snippet most tutorials hand you scores 0.405 on Karate Club with default cross-validation - worse than the 0.5 you get by always guessing the majority class. Fix the split and the same features reach 0.657. Then something stranger happens: eigenvector centrality on its own scores 0.717, beating all nine columns combined, with a paired t-test p-value of 0.0022.
Every number in this article comes from code I ran on NetworkX 3.7, pandas 3.0.6, scikit-learn 1.9.1 and NumPy 2.5.3, on CPU. Nothing here is projected.
Why Structural Features Still Earn Their Place
Graph neural networks learn features automatically, but classical features give you three things a GNN does not:
- Speed. Nine columns for 1,000 nodes took 1.82 seconds on CPU, and that included sampled betweenness. A gradient-boosted model on those columns trains in seconds.
- Interpretability. "High betweenness" is a sentence you can say to a stakeholder. A 64-dimensional learned embedding is not.
- A baseline. A GNN that cannot beat a random forest on structural columns is not paying for its complexity.
They also matter when your nodes have no attributes at all. Many GNN pipelines fall back on degree or PageRank as input features for exactly that reason, so the same numbers serve both worlds.
Step 1: Build the Graph
NetworkX loads an edge list from pandas directly:
import numpy as np
import pandas as pd
import networkx as nx
edges = pd.DataFrame({"src": ["a", "a", "b", "c", "d"],
"dst": ["b", "c", "c", "d", "e"],
"weight": [3, 1, 2, 5, 1]})
G = nx.from_pandas_edgelist(edges, "src", "dst", edge_attr="weight") # undirected
# nx.from_pandas_edgelist(..., create_using=nx.DiGraph) for directed graphs
print(type(G).__name__, G.number_of_nodes(), G.number_of_edges(), G["a"]["b"]["weight"])
Graph 5 5 3
Decide early whether the graph is directed, weighted, or a multigraph, because that choice changes what every measure means. Citations, follows and email flows are directed. Friendships usually are not. A multigraph will quietly break algorithms that assume one edge per pair.
Step 2: Centrality in Plain English
Centrality asks "how important is this node?" The trouble is that "important" has several definitions, and they disagree.
| Measure | Question it answers | Cost on a graph with V nodes and E edges |
|---|---|---|
| Degree | How many neighbours does it have? | O(E) |
| Betweenness | How often does it sit on shortest paths? | O(V·E) exact, O(k·E) with k sampled pivots |
| Closeness | How near is it to everything else? | O(V·E) |
| Eigenvector | Does it connect to already-important nodes? | Iterative, can fail to converge |
| PageRank | Importance from a random walk over important neighbours | Iterative, handles directed graphs |
On Karate Club the definitions separate cleanly. Node 0 scores 0.089 PageRank, 0.438 betweenness and 0.355 eigenvector. Node 3 scores 0.037, 0.012 and 0.211. Node 0 is the hub everyone passes through. Node 3 is well connected inside one cluster and irrelevant as a bridge. Two reasonable questions, two different answers, and neither is wrong.
Step 3: Turn Centralities Into a Feature Table
def structural_features(G, seed=0):
H = nx.Graph(G) # simple undirected view
H.remove_edges_from(nx.selfloop_edges(H)) # core_number rejects self-loops
feats = pd.DataFrame(index=list(H.nodes))
feats["degree"] = pd.Series(dict(H.degree()))
feats["log_degree"] = np.log1p(feats["degree"]) # degree is heavy-tailed
feats["clustering"] = pd.Series(nx.clustering(H))
feats["triangles"] = pd.Series(nx.triangles(H))
feats["core_number"] = pd.Series(nx.core_number(H))
feats["pagerank"] = pd.Series(nx.pagerank(G, alpha=0.85)) # G keeps direction
feats["closeness"] = pd.Series(nx.closeness_centrality(H))
k = min(200, H.number_of_nodes()) # sample pivots to approximate betweenness
feats["betweenness"] = pd.Series(nx.betweenness_centrality(H, k=k, seed=seed))
try:
feats["eigenvector"] = pd.Series(nx.eigenvector_centrality(H, max_iter=500))
except nx.PowerIterationFailedConvergence:
feats["eigenvector"] = np.nan # drop or replace with another measure
return feats
Four details in that function are load-bearing:
- The self-loop removal is not optional.
nx.core_numberon a graph with a self-loop raisesNetworkXNotImplemented: Input graph has self loops which is not permitted. I triggered it with a two-edge graph and got that exact exception, so the cleanup line earns its place. k = min(200, n)is exact on small graphs. On Karate Club, k equals n equals 34, so the "approximation" is the full computation. Sampling only saves time when k is strictly smaller than n.- Eigenvector centrality needs the guard. On Karate Club it converged, but it raises
PowerIterationFailedConvergenceon graphs where the iteration oscillates. An unguarded call crashes the whole feature build. - PageRank runs on
G, everything else onH. That is deliberate: PageRank is the one measure here that respects edge direction.
The measured output for the first eight nodes of Karate Club:
degree log_degree clustering triangles core_number pagerank closeness betweenness eigenvector
0 16 2.833 0.150 18 4 0.089 0.569 0.438 0.355
1 9 2.303 0.333 12 4 0.057 0.485 0.054 0.266
2 10 2.398 0.244 11 4 0.063 0.559 0.144 0.317
3 6 1.946 0.667 10 4 0.037 0.465 0.012 0.211
4 3 1.386 0.667 2 3 0.021 0.379 0.001 0.076
5 4 1.609 0.500 3 3 0.034 0.384 0.030 0.079
6 4 1.609 0.500 3 3 0.032 0.384 0.030 0.079
7 4 1.609 1.000 6 4 0.026 0.440 0.000 0.171
Nine columns, 34 rows, no missing values.
The Nine Columns Are Mostly One Column
Before you celebrate nine features, look at how much they overlap. Spearman correlation with degree on Karate Club:
| Feature | Spearman vs degree |
|---|---|
| PageRank | 0.94 |
| Core number | 0.93 |
| Triangles | 0.92 |
| Betweenness | 0.90 |
| Closeness | 0.89 |
| Eigenvector | 0.78 |
| Clustering | -0.53 |
Six of the nine columns carry between 0.78 and 0.94 of the degree ranking. On a 1,000-node planted-partition graph it gets worse: PageRank and log-degree are 1.00 correlated with degree, eigenvector 0.94, closeness 0.89, betweenness 0.83.
That is not a curiosity. It is the reason the next experiment behaves the way it does. You are not adding nine features. You are adding one feature nine times, each copy with a different amount of noise.
Step 4: Communities
Community detection finds densely connected groups. On Karate Club, three standard algorithms disagree:
communities = nx.community.louvain_communities(K, seed=0) # list of sets of nodes
print("communities:", len(communities))
print("modularity:", round(nx.community.modularity(K, communities), 3))
louvain communities: 4 | sizes: [4, 5, 11, 14] | modularity: 0.444
greedy modularity: 3 communities | modularity: 0.411
label propagation: 3 communities | modularity: 0.309
Louvain finds four groups at modularity 0.444, greedy modularity finds three at 0.411, and label propagation finds three at 0.309. Modularity 0.309 versus 0.444 is a large gap on a graph this small, and it is the first hint that "fast" and "correct" are separate properties.
The gap becomes dramatic at scale. I generated a planted-partition graph with 5 blocks of 200 nodes, 6,478 edges, and a known ground-truth assignment, then scored each algorithm against it:
| Algorithm | Communities found | ARI vs truth | Time |
|---|---|---|---|
| Louvain | 5 | 0.992 | 0.08 s |
| Greedy modularity | 5 | 0.917 | 1.64 s |
| Label propagation | 1 | 0.000 | 0.04 s |
Label propagation returned a single community containing all 1,000 nodes. It is the fastest of the three and it found nothing. If you use it, print the community count before you trust anything downstream.
Check That Your Communities Are Stable
Louvain is randomized. Ten seeds on Karate Club:
from sklearn.metrics import adjusted_rand_score
def to_labels(comms, nodes):
m = {n: i for i, c in enumerate(comms) for n in c}
return [m[n] for n in nodes]
nodes = list(H.nodes)
runs = [nx.community.louvain_communities(H, seed=s) for s in range(10)]
base = to_labels(runs[0], nodes)
print([round(adjusted_rand_score(base, to_labels(r, nodes)), 2) for r in runs[1:]])
ARI across 10 seeds: [1.0, 0.86, 1.0, 0.78, 1.0, 1.0, 0.76, 1.0, 1.0] | min 0.76
sizes per seed: [4,5,11,14] x7, [5,6,11,12], [4,6,10,14], [5,11,18]
Eight of nine comparisons were either identical or close, but one seed merged two groups into [5, 11, 18]. Scores near 1.0 mean the structure is robust. A single run that happens to be the merged one gives you a feature column describing a partition that does not exist. Run the algorithm several times and compare, or you are reporting one draw as if it were the truth.
Turn Communities Into Features
Raw community IDs make poor features: the numbers are arbitrary labels that change between runs. Use properties that carry meaning instead:
membership = {n: i for i, c in enumerate(communities) for n in c}
sizes = {i: len(c) for i, c in enumerate(communities)}
feats["community_size"] = pd.Series({n: sizes[membership[n]] for n in H})
def internal_fraction(H, membership):
out = {}
for n in H:
nbrs = list(H.neighbors(n))
out[n] = (sum(membership[m] == membership[n] for m in nbrs) / len(nbrs)) if nbrs else np.nan
return pd.Series(out)
feats["internal_frac"] = internal_fraction(H, membership) # 1.0 = all neighbours in my community
internal_frac separates nodes buried inside a community from bridges that straddle several. On the 1,000-node planted-partition graph, the mean internal fraction was 0.76 using the true blocks and 0.76 using Louvain's communities, with a Spearman correlation of 0.995 between the two columns. When the detector is accurate, the feature built from its output is nearly identical to the oracle feature - which is exactly what you want, and a good way to sanity-check a community pipeline.
Step 5: Feed Features to a Standard Model
Now treat the table like any tabular dataset. This demo uses Karate Club, which is tiny, so the numbers are a smoke test rather than a benchmark:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
K = nx.karate_club_graph()
X = structural_features(K).fillna(0)
y = pd.Series({n: int(K.nodes[n]["club"] == "Officer") for n in K.nodes}).loc[X.index]
scores = cross_val_score(RandomForestClassifier(n_estimators=300, random_state=0), X, y, cv=5)
print("5-fold accuracy:", scores.mean().round(3))
5-fold accuracy: 0.405
folds: [0.571 0.429 0.571 0.286 0.167]
0.405. The model is worse than always answering "not an Officer", which scores 0.5 because 17 of 34 members belong to each club.
This is not a graph problem. It is a splitting problem. cross_val_score with a classifier and an integer cv uses stratified folds without shuffling, and Karate Club's node ids happen to run in club order: nodes 0 through 8 are all one club, node 9 is the other. The fold label means confirm it:
fold label means: [0.0, 0.14, 0.57, 0.86, 1.0]
Each fold is a different classification problem. Fold one has no positive examples at all. Any dataset whose row order correlates with the label will produce this, and graph datasets do it constantly because node ids often come from the order in which a crawl, a file, or a community was generated.
Shuffle the folds and the same model, same features, same seed gives a different story. Repeating 5-fold stratified cross-validation ten times (50 fits):
| Setup | Accuracy |
|---|---|
Default cv=5, no shuffle |
0.405 ± 0.159 |
StratifiedKFold(shuffle=True), 5×10 |
0.657 ± 0.168 |
| Label permutation control, 5×10 | 0.496 ± 0.090 |
The permutation control is the number to keep. Shuffle the labels and the identical pipeline lands at 0.496, dead on chance. That means 0.657 is real signal reaching the model through the graph structure, not leakage. Run this control before you believe any graph-feature result, because structural features are computed from the same graph the labels live on and are unusually good at smuggling information.
When Nine Features Lose to One
The corrected number still hides a surprise. Single-column models, same 50-fold protocol:
| Feature alone | Accuracy |
|---|---|
| Eigenvector | 0.717 ± 0.149 |
| PageRank | 0.672 ± 0.154 |
| Triangles | 0.591 ± 0.151 |
| Core number | 0.587 ± 0.169 |
| Closeness | 0.581 ± 0.125 |
| Betweenness | 0.518 ± 0.113 |
| Clustering | 0.460 ± 0.140 |
| Degree | 0.364 ± 0.164 |
| Log degree | 0.364 ± 0.169 |
| All nine together | 0.657 ± 0.168 |
One column beats all nine. The paired difference across the same 50 folds is -0.060 ± 0.130, t = -3.23, p = 0.0022, and a Wilcoxon signed-rank test gives p = 0.0047. That is not a fluke of one split.
The feature importances explain it:
eigenvector 0.275 | closeness 0.134 | pagerank 0.130 | betweenness 0.118 | triangles 0.111
clustering 0.090 | log_degree 0.057 | core_number 0.044 | degree 0.042
The importances look reassuringly spread out - nothing dominates, the top column only takes 0.275. But with six columns carrying the same ranking, each tree in the forest splits on a different near-duplicate, and the ensemble's votes scatter across correlated columns instead of concentrating on the one that matters. Feature importance looks healthy while the model is measurably worse than a single column. That is the trap.
Two more results from the same protocol:
- Logistic regression on all nine columns scores 0.463 ± 0.146, near chance. Raw structural features are heavy-tailed and collinear, so a linear model cannot use them without a transform.
- Degree plus PageRank together scores 0.560 ± 0.161, worse than PageRank alone. Adding the most correlated pair of columns to each other helps nobody.
Structure Alone Cannot Recover Communities
Here is the honest limit of the whole approach, measured on the 1,000-node planted-partition graph where I know the true block of every node:
| Features | Accuracy at predicting the true block |
|---|---|
| All nine structural columns | 0.315 |
| Eigenvector only | 0.227 |
| Degree only | 0.211 |
| Chance (5 balanced blocks) | 0.200 |
Centrality features barely beat chance at identifying which block a node belongs to. The reason is structural: a planted-partition graph gives every block the same size and density, so every node has nearly the same degree regardless of which block it sits in. The communities were recoverable - Louvain hit ARI 0.992 - but only through the membership features, not through the centrality columns.
So the practical rule is: if your label is "which group is this node in", add community_size and internal_frac. Do not expect PageRank to find the answer, because centrality measures position, not membership.
Graph-Level Features
For graph classification or regression with classic models, summarize each whole graph as one row:
def graph_features(G):
H = nx.Graph(G)
comps = list(nx.connected_components(H))
giant = H.subgraph(max(comps, key=len))
deg = np.array([d for _, d in H.degree()])
return {
"n_nodes": H.number_of_nodes(),
"n_edges": H.number_of_edges(),
"density": nx.density(H),
"avg_degree": deg.mean(),
"max_degree": deg.max(),
"avg_clustering": nx.average_clustering(H),
"transitivity": nx.transitivity(H),
"n_components": len(comps),
"giant_frac": giant.number_of_nodes() / H.number_of_nodes(),
"assortativity": nx.degree_assortativity_coefficient(H),
"diameter_giant": nx.diameter(giant) if giant.number_of_nodes() > 1 else 0,
}
Karate Club through that function:
{'n_nodes': 34, 'n_edges': 78, 'density': 0.139, 'avg_degree': 4.588, 'max_degree': 17,
'avg_clustering': 0.571, 'transitivity': 0.256, 'n_components': 1, 'giant_frac': 1.0,
'assortativity': -0.476, 'diameter_giant': 5}
The assortativity of -0.476 says the hubs connect to non-hubs, which is the structural reason degree alone predicts so little here. Diameter and average path length need a connected graph, which is why the code measures the largest component, and they are expensive on big graphs. For molecules or other small graphs this works fine, and it makes a solid baseline against a learned graph classification model.
Leakage Rules That Actually Bite
Graph features leak more easily than tabular ones. I measured how much: remove 8 of Karate Club's 78 edges (about 10%), recompute every feature, and compare.
| Feature | Rank correlation, full vs truncated | Nodes that changed |
|---|---|---|
| PageRank | 0.944 | 34 of 34 |
| Betweenness | 0.913 | 23 of 34 |
| Degree | 0.912 | 14 of 34 |
| Clustering | 0.588 | 17 of 34 |
PageRank changed on every single node when 10% of edges disappeared. If you compute features on the complete graph and then evaluate link prediction on hidden edges, you have encoded the answer. Clustering is the most fragile of the four at 0.588, because removing one edge destroys a triangle outright.
The checklist:
- Link prediction: compute features after removing test edges, and keep both directions of an undirected edge in the same split.
- Node classification: purely structural features do not use labels, so computing them on the full graph is a normal transductive setup. Any feature built from labels, such as "fraction of neighbours in class A", must use training labels only.
- Temporal tasks: compute features from the graph as of prediction time, never from the future.
- Community features: if you tuned the algorithm against test labels, you have leaked, even though the algorithm itself never saw a label.
- Cross-graph comparisons: normalize size-dependent features. A diameter on 50 nodes and a diameter on 5,000 do not compare.
Choosing Between These and a GNN
- Use NetworkX features when you need a fast baseline, interpretability, small data, or no GPU.
- Use a GNN when node attributes matter, when relationships are complex, and when you can train and tune it fairly against the baseline.
- Combine them. Feed structural features into a GNN as node inputs when attributes are missing, or concatenate them with learned embeddings, and check on validation data whether the combination helps.
A GNN that cannot beat a random forest on ten structural columns deserves suspicion. On Karate Club the bar is 0.717 from a single column, so a model that reports 0.70 has not demonstrated anything. If you want the other side of that comparison, GCN vs GraphSAGE vs GAT runs the same kind of honest baseline argument for the neural side.
Common Pitfalls
- Using unshuffled cross-validation on a graph. It cost me 0.25 accuracy on Karate Club before I noticed. Check the fold label means.
- Assuming more columns mean a better model. Nine columns scored 0.657; one scored 0.717, at p = 0.0022.
- Computing betweenness on a large graph without sampling. Pass
k, and rememberk = nis exact, not approximate. - Using raw community IDs as features. They are arbitrary labels that change between seeds.
- Ignoring edge weight semantics. In shortest-path measures NetworkX treats weight as distance; in PageRank it treats weight as strength. I built a triangle with weights 1, 1 and 10: weighted shortest path from A to C goes A-B-C at length 2, while unweighted it goes straight A-C. PageRank gave A and C 0.441 each and B 0.118.
- Assuming disconnected graphs raise errors. They often do not. On a two-component graph, closeness returned values (0.333, 0.5, 0.25) and eigenvector returned 1.06e-05 for the isolated pair instead of failing. Silent near-zero scores are worse than a crash.
- Feeding raw heavy-tailed values to a linear model. Logistic regression on nine raw columns scored 0.463. Transform or rank first.
- Skipping the permutation control. Without it, 0.657 on 34 nodes means nothing.
- Reporting one seed. One of my ten Louvain seeds merged two communities; label propagation found one community where five existed.
- Treating centrality as causal influence. High PageRank describes position in a graph, not impact in the world.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Complex Network Analysis in Python | a NetworkX-first tour of the measures in this article, written for exactly the workflow where you have a graph and a tabular toolkit rather than a GPU cluster. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it with the notebook open. The book explains what each measure means; only the run tells you that six of them are the same column in disguise on your graph.
Wrapping Up
NetworkX gives you a short path from a graph to a feature table: centralities describe a node's position, communities describe its neighbourhood, and graph-level statistics describe the whole structure. Feed those into a standard model, validate the communities, and guard against leakage.
The numbers from my run: the tutorial snippet scores 0.405 unshuffled, 0.657 with proper stratified folds, and 0.717 with eigenvector centrality alone. Louvain recovered planted communities at ARI 0.992; label propagation returned one community for five. PageRank changed on all 34 nodes when I removed 10% of the edges.
So run structural_features on a graph you care about this week, train a random forest on the output, and check the feature importances. If one measure dominates, you just learned what drives your problem. If all nine are correlated with degree, you learned that too - and that is worth knowing before you build a GNN. For a gentler introduction to the concepts behind these measures, start with Graph Machine Learning for Beginners.
Frequently Asked Questions
Can I use NetworkX features with scikit-learn?
Yes. Build a DataFrame indexed by node id, one column per structural measure, and pass it to any tabular model. On Karate Club I got nine columns for 34 nodes in well under a second, and 1,000 nodes took 1.82 seconds including sampled betweenness. The node id must become the index so labels line up.
Why did my 5-fold accuracy come out below 50 percent?
Because cross_val_score with a classifier uses stratified folds without shuffling. Karate Club's node ids run in club order, so each contiguous fold held almost a single class and fold label means were 0.0, 0.14, 0.57, 0.86 and 1.0. The same model scored 0.405 that way and 0.657 with shuffled stratified folds.
Do more graph features make the model better?
Not automatically. On Karate Club, all nine structural columns scored 0.657 over 50 folds while eigenvector centrality alone scored 0.717, a paired difference of -0.060 with p = 0.0022. Six of the nine columns correlated 0.78 to 0.94 with degree, so the ensemble split on near-duplicates instead of adding information.
Which community detection algorithm should I use?
Start with Louvain. On a 1,000-node planted-partition graph it recovered 5 communities at ARI 0.992 in 0.08 seconds, while greedy modularity reached 0.917 in 1.64 seconds and label propagation collapsed into a single community at ARI 0.000. Label propagation is fast, not reliable, so check the community count before trusting it.
How do I avoid leakage when computing structural features?
Recompute features on the graph that excludes every held-out edge. When I removed 8 of 78 Karate Club edges, PageRank changed on all 34 nodes and clustering changed on 17, with rank correlation dropping to 0.588. Features computed on the full graph encode the answer you are trying to predict.
Sources
[1]NetworkX, Centrality - the reference for degree, betweenness, closeness, eigenvector and PageRank, including thekpivot argument and convergence behaviour: networkx.org[2]NetworkX, Communities - Louvain, greedy modularity, label propagation and modularity scoring in one place: networkx.org[3]Blondel et al., Fast unfolding of communities in large networks - the Louvain paper, including the modularity gain formula and the resolution limit: arxiv.org[4]Fortunato, Community detection in graphs - why modularity-based methods have a resolution limit and why label propagation can collapse: arxiv.org[5]Newman, The structure and function of complex networks - the source for centrality definitions, assortativity and the meaning of edge weights in path-based measures: arxiv.org
