The one-line mental model
Graph data science treats entities as nodes and relationships as edges: centrality measures rank influence, community detection finds clusters, and graph neural networks learn node representations by averaging features along those edges.
You will be able to:
- Build a property graph in NetworkX and measure degree, PageRank, and betweenness centrality
- Detect communities with greedy modularity and Louvain methods
- Compute node embeddings with Node2Vec and use them in downstream models
- Explain message passing in a graph neural network layer
Prerequisites
- !Python dictionaries and sets
- !Pandas DataFrames
- !Basic linear algebra (vectors, matrix multiply)
What You'll Learn
- 1Choose the right centrality measure for a given question
- 2Run community detection and interpret modularity scores
- 3Generate node embeddings and feed them into a classifier
- 4Describe how a GNN aggregates neighborhood information
Modeling entities and relationships
A graph is a pair G = (V, E): nodes (vertices) represent entities and edges represent relationships. An edge can be undirected (friendship) or directed (following), weighted (transaction amount) or unweighted, and nodes can carry arbitrary attributes â the property graph model. Choosing the right abstraction is the first modeling decision: do purchases connect users to products (bipartite), or users to users who buy the same items (projected)? Each choice changes every downstream metric.
import networkx as nx
import pandas as pd
edges = pd.DataFrame({
"src": ["alice", "alice", "bob", "bob", "carol",
"dave", "eve", "frank", "grace", "heidi"],
"dst": ["bob", "carol", "carol", "dave", "eve",
"frank", "frank", "grace", "heidi", "alice"],
"weight": [3, 5, 2, 4, 6, 1, 3, 2, 4, 5],
})
G = nx.from_pandas_edgelist(
edges, source="src", target="dst",
edge_attr="weight", create_using=nx.DiGraph,
)
print(f"Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}")
print(f"Density: {nx.density(G):.3f}")
print(f"Is strongly connected: {nx.is_strongly_connected(G)}")
components = list(nx.strongly_connected_components(G))
print(f"Strongly connected components: {len(components)}")
for comp in sorted(components, key=len, reverse=True):
print(f" size {len(comp)}: {sorted(comp)}")
Directed graphs need separate in-degree and out-degree â a Twitter-style account can follow thousands (high out-degree) while being followed by few (low in-degree). Weakly connected components ignore edge direction and are often the right first look at fragmentation.
Centrality: who matters most
Centrality scores answer "which node is most important" under different definitions. Degree counts direct neighbors and is a coarse popularity proxy. Betweenness counts shortest paths passing through a node, exposing bridges between clusters. Closeness measures how quickly a node reaches the rest of the graph. PageRank generalizes importance by assuming a random surfer who follows edges and occasionally teleports, so links from important nodes count more.
where d is the damping factor (usually 0.85), B_u is the set of nodes linking to u, and L(v) is the out-degree of v.
degree_cent = nx.degree_centrality(G)
between_cent = nx.betweenness_centrality(G, weight="weight")
closeness_cent = nx.closeness_centrality(G)
pagerank = nx.pagerank(G, alpha=0.85, weight="weight")
centrality = pd.DataFrame({
"degree": degree_cent,
"betweenness": between_cent,
"closeness": closeness_cent,
"pagerank": pagerank,
}).round(4)
print(centrality.sort_values("pagerank", ascending=False))
print(f"\nTop bridge node (betweenness): "
f"{max(between_cent, key=between_cent.get)}")
A node can top one ranking and languish on another â a hub in a tight cluster may have huge degree but near-zero betweenness, because no shortest path detours through it. Always match the measure to the business question: influence for diffusion, betweenness for risk of network fragmentation, closeness for speed of information spread.
Community detection: finding the clusters
Communities are groups of nodes more densely connected to each other than to the rest of the graph. Modularity is the standard quality function: it compares the observed edge density inside groups against what a random graph with the same degree distribution would produce. Louvain and greedy modularity both optimize modularity by local moves, with Louvain typically faster on large graphs.
import matplotlib.pyplot as plt
G_und = G.to_undirected()
communities = nx.community.greedy_modularity_communities(
G_und, weight="weight",
)
modularity = nx.community.modularity(G_und, communities, weight="weight")
for i, comm in enumerate(communities, 1):
print(f"Community {i}: {sorted(comm)}")
print(f"Modularity: {modularity:.4f}")
try:
from networkx.algorithms.community import louvain_communities
louvain = louvain_communities(G_und, weight="weight", seed=42)
print(f"Louvain communities: {[sorted(c) for c in louvain]}")
print(f"Louvain modularity: "
f"{nx.community.modularity(G_und, louvain, weight='weight'):.4f}")
except ImportError:
print("louvain_communities unavailable in this NetworkX version")
pos = nx.spring_layout(G_und, seed=42, k=1.5)
colors = []
for node in G_und.nodes():
for i, comm in enumerate(communities):
if node in comm:
colors.append(i)
break
plt.figure(figsize=(8, 6))
nx.draw(G_und, pos, with_labels=True, node_color=colors,
cmap="Set2", node_size=900, font_size=10,
edge_color="gray", width=2)
plt.title(f"Communities (modularity={modularity:.3f})")
plt.tight_layout()
plt.show()
Modularity above roughly 0.3 indicates real community structure; near-zero values mean the partition is no better than random. Very high scores (0.7+) can signal a fragmented graph where every community is almost disconnected â a red flag, not a triumph. Resolution limits also exist: modularity optimization will miss small, tight clusters inside large ones.
Node embeddings: Node2Vec and friends
Rather than hand-crafting features, embedding methods learn a dense vector per node such that nodes with similar structural roles land near each other. Node2Vec random-walks the graph, feeds the walk sequences into Word2Vec, and treats each node like a word appearing in the contexts of its walk-neighbors. The p and q parameters bias walks toward breadth-first (local structure) or depth-first (structural equivalence) exploration.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
try:
from node2vec import Node2Vec
node2vec = Node2Vec(
G_und, dimensions=64, walk_length=20, num_walks=50,
p=1.0, q=2.0, workers=1, seed=42,
)
model = node2vec.fit(window=10, min_count=1, batch_words=4)
embeddings = pd.DataFrame(
{n: model.wv[str(n)] for n in G_und.nodes()},
).T
print(f"Embedding matrix: {embeddings.shape}")
print(embeddings.iloc[:3, :6].round(3))
except ImportError:
rng = np.random.default_rng(42)
embeddings = pd.DataFrame(
rng.normal(size=(G_und.number_of_nodes(), 16)),
index=list(G_und.nodes()),
)
print("node2vec unavailable; using random embeddings for demo")
community_id = {}
for i, comm in enumerate(communities):
for node in comm:
community_id[node] = i
emb_with_label = embeddings.copy()
emb_with_label["label"] = emb_with_label.index.map(community_id)
clf = RandomForestClassifier(n_estimators=100, random_state=42)
scores = cross_val_score(
clf,
emb_with_label.drop(columns="label"),
emb_with_label["label"],
cv=min(3, emb_with_label["label"].value_counts().min()),
)
print(f"Community-prediction CV accuracy from embeddings: "
f"{scores.mean():.3f}")
High cross-validated accuracy means the embeddings already encode community structure â useful as features for fraud detection, recommendation, or any node-level classification where labels are scarce.
Graph neural networks: message passing
Graph neural networks learn node representations by iterative message passing: each layer aggregates features from a node's neighbors, transforms them with a weight matrix, and combines them with the node's own features. After several layers, every node's embedding encodes its k-hop neighborhood â the graph analog of a convolution, but on irregular topology.
import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from torch_geometric.data import Data
node_list = list(G_und.nodes())
node_idx = {n: i for i, n in enumerate(node_list)}
x = torch.tensor(embeddings.values, dtype=torch.float)
edge_index = torch.tensor(
[[node_idx[u], node_idx[v]] for u, v in G_und.edges()],
dtype=torch.long,
).t().contiguous()
y = torch.tensor([community_id[n] for n in node_list], dtype=torch.long)
data = Data(x=x, edge_index=edge_index, y=y)
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels):
super().__init__()
self.conv1 = GCNConv(in_channels, hidden_channels)
self.conv2 = GCNConv(hidden_channels, out_channels)
def forward(self, data):
x, edge_index = data.x, data.edge_index
x = self.conv1(x, edge_index)
x = F.relu(x)
x = F.dropout(x, p=0.5, training=self.training)
return self.conv2(x, edge_index)
torch.manual_seed(42)
gcn = GCN(x.shape[1], 32, int(y.max()) + 1)
optimizer = torch.optim.Adam(gcn.parameters(), lr=0.01)
gcn.train()
for epoch in range(200):
optimizer.zero_grad()
out = gcn(data)
loss = F.cross_entropy(out, y)
loss.backward()
optimizer.step()
if (epoch + 1) % 50 == 0:
preds = out.argmax(dim=1)
acc = (preds == y).float().mean()
print(f"Epoch {epoch + 1:3d} loss={loss.item():.4f} "
f"train acc={acc:.3f}")
The most common pitfall is over-squashing: after many layers, a node's representation must compress an exponentially growing neighborhood, and signal from distant nodes vanishes. In practice two to three GCN layers are standard; deeper stacks need specialized architectures like GraphSAGE or attention-based GAT layers.
When to use graphs â and when not to
Graph models shine when relationships carry signal: fraud rings, supply chains, knowledge bases, social platforms, and molecular structures. They are the wrong tool when interactions are weak, when the graph is nearly complete (everyone connected to everyone), or when you lack the engineering capacity to maintain a graph store and feature pipelines. Start with relational joins and non-graph baselines, measure how much predictive lift edges actually provide, and only then invest in GNN infrastructure.
The engineering cost of a graph stack is real: graph databases (Neo4j, TigerGraph) or specialized analytical frameworks (PyG, DGL) have their own operational requirements, and feature pipelines that extract node and edge attributes are more complex than standard tabular ETL. A pragmatic path is to start with a relational representation â precompute neighbor aggregates as SQL joins, run classical models, and measure the lift. If that lift is meaningful and the relationships are core to the product, graduate to a proper graph stack. If the lift is marginal, the relational approach was the right call all along, and you avoided months of infrastructure work.