TGraphX › Insights › Graph Mining vs GNN Message Passing: When to Use Each
← Back to Insights

Graph Mining vs GNN Message Passing: When to Use Each

Topic: Graph mining, generation, optimization and RL

Graph mining and graph neural networks (GNNs) both work on graph-structured data, but they start from different places. Mining computes a quantity that you define in advance: a degree, a triangle count, a shortest path, a community assignment. A GNN learns, from an objective, which function of the features and the neighbourhood to compute.

This article explains where the two diverge, shows the TGraphX calls for both, and runs one small experiment where message passing helps or hurts, depending on how the labels are generated. Examples tested with TGraphX 1.5.1 on CPU.


Graph mining: what it is

Graph mining extracts patterns and structural properties from a graph without task labels. Typical families:

  • Centrality: degree, betweenness, closeness, eigenvector centrality, PageRank
  • Motifs: triangles, paths, small cliques, clustering coefficients
  • Community detection: label propagation, spectral clustering, Louvain-style methods
  • Graph similarity: graph edit distance, Weisfeiler-Lehman (WL) kernels, spectral distances
  • Paths: breadth-first search, Dijkstra, Floyd-Warshall
  • Random-walk embeddings: DeepWalk and Node2Vec

That list is mining in general. tgraphx.mining implements a subset: for example, it has no Louvain, and its motif counting covers only a few small patterns, mainly wedges and triangles.

These methods are not all alike. Degrees, triangle counts, WL refinement and exact shortest paths are deterministic functions of the input. Community detection and spectral clustering often involve random choices, and a graph need not have one correct community assignment. Node2Vec sits in between the two worlds: it is trained, but on random walks rather than on task labels.


GNN message passing: what it is

A message-passing GNN updates every node from its neighbours, layer by layer (Gilmer et al., 2017):

m_v^(k) = AGG over u in N(v) of  MSG^(k)( h_v^(k-1), h_u^(k-1), e_uv )
h_v^(k) = UPDATE^(k)( h_v^(k-1), m_v^(k) ),      with h_v^(0) = x_v

x_v are the node features, e_uv the optional edge features, and AGG is order-independent (sum, mean, max, attention). The weights inside MSG and UPDATE are fitted to a loss. That loss is most often supervised (node classes, graph properties, links), but it can also be self-supervised, as in graph autoencoders (Kipf and Welling, 2016) or Deep Graph Infomax (Veličković et al., 2019).


When graph mining is the better tool

  • The question is defined by the graph itself. Shortest paths, degree distributions and triangle counts have exact algorithms. A trained model would only approximate them.
  • You have no labels and no informative features. Mining works immediately. A self-supervised GNN is possible, but it adds a training and evaluation problem.
  • You need a quantity you can explain. "This node has high betweenness" has a precise definition. A learned embedding does not come with one.
  • You need a baseline. Structural features plus a simple classifier cost little and tell you how hard the task is.

When a GNN is the better tool

  • Node or edge features carry signal that has to be combined with the topology. Purely structural mining does not look at them.
  • You have a target to predict and enough labelled examples to fit and validate a model.
  • New nodes or graphs arrive later. A message-passing GNN with shared weights can be applied to unseen nodes that have features and edges. Mined features must be recomputed, and Node2Vec has no vector for a node it never saw.
  • The features are tensors, such as image patches [C, H, W], and you want to keep their layout.

Mining with TGraphX

The single-graph measures in tgraphx.mining used below take (edge_index, num_nodes), not a Graph. List both directions of every undirected edge.

python
import torch
from tgraphx import mining

# Zachary's karate club: 34 nodes, 78 undirected edges listed in both directions.
edge_index, n = mining.karate_club_graph()

summary = mining.graph_summary(edge_index, num_nodes=n, directed=False)
print({k: summary[k] for k in ("num_nodes", "num_edges", "density", "num_connected_components")})
# {'num_nodes': 34, 'num_edges': 156, 'density': 0.13903743, 'num_connected_components': 1}

print(mining.triangle_count(edge_index, n))                                     # 45
clustering = mining.local_clustering_coefficient(edge_index, n)
print(round(clustering.mean().item(), 4))                                       # 0.5706

pagerank = mining.pagerank(edge_index, n)
# betweenness_centrality returns twice the textbook value in 1.5.1, hence the / 2
betweenness = mining.betweenness_centrality(edge_index, n) / 2
print(pagerank.topk(3).indices.tolist(), betweenness.topk(3).indices.tolist())  # [33, 0, 32] [0, 33, 32]

# Weisfeiler-Lehman colour refinement: one structural "colour" per node and round
colours = mining.weisfeiler_lehman_labels(edge_index, n, num_iterations=3)
print([len(set(round_)) for round_ in colours])                                 # [11, 27, 27, 27]

num_edges counts the columns of edge_index, so each undirected edge appears twice. To compare WL features between graphs, read the motif discovery guide first: in 1.5.1, wl_graph_features and wl_kernel_matrix number colours separately for each graph, which can make isomorphic graphs look different.

What message passing cannot see

Standard message-passing GNNs are at most as discriminative as the 1-WL colour refinement test (Xu et al., 2019; Morris et al., 2019). A consequence: two triangles and a six-node ring look the same to them when all node features are equal, because every node has two identical neighbours.

python
from tgraphx import GCNConv

def undirected(edges):
    e = torch.tensor(edges).t()
    return torch.cat([e, e.flip(0)], dim=1)

two_triangles = undirected([(0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3)])
hexagon = undirected([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)])

torch.manual_seed(0)
conv1, conv2 = GCNConv(4, 8), GCNConv(8, 8)
x = torch.ones(6, 4)

def encode(ei):
    return conv2(torch.relu(conv1(x, ei)), ei)

print(torch.allclose(encode(two_triangles), encode(hexagon)))                           # True
print(mining.triangle_count(two_triangles, 6), mining.triangle_count(hexagon, 6))       # 2 0

Randomly initialised or fully trained, these layers give both graphs the same node embeddings. A mined triangle count separates them at once, so adding structural features can give a GNN information it could not compute itself.


One experiment, two answers

The script below builds graphs with three communities and noisy node features (one graph per seed), with 20% of the nodes for training, 20% for validation and 60% for test. It runs the same four models in two situations:

  1. the label of a node is its community (structure matters);
  2. the label is drawn at random, independently of the graph, and only the features carry it.

Node2Vec embeddings are trained without labels on the whole graph, which is the usual transductive setting for node classification. For link prediction you would have to train them on the training edges only.

python
import torch.nn as nn
import torch.nn.functional as F
import tgraphx as tgx
from tgraphx.estimators import EarlyStopping, node_train_val_test_split
from tgraphx.mining.node2vec import node2vec_walks, generate_skipgram_pairs, Node2VecEmbedding

def node2vec(edge_index, n, seed):
    torch.manual_seed(seed)
    walks = node2vec_walks(edge_index, n, walk_length=10, walks_per_node=5, seed=seed)
    centers, contexts, negatives = generate_skipgram_pairs(
        walks, window_size=5, negative_ratio=5, num_nodes=n, seed=seed)
    negatives = negatives.view(centers.numel(), -1)
    model = Node2VecEmbedding(n, embedding_dim=16)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
    for _ in range(2):
        for batch in torch.randperm(centers.numel()).split(2048):
            optimizer.zero_grad()
            model(centers[batch], contexts[batch], negatives[batch].flatten()).backward()
            optimizer.step()
    return model.get_embeddings()

class LogisticRegression(nn.Module):
    def __init__(self, in_dim, num_classes):
        super().__init__()
        self.linear = nn.Linear(in_dim, num_classes)

    def forward(self, x, edge_index):          # ignores the graph
        return self.linear(x)

class GCN(nn.Module):
    def __init__(self, in_dim, num_classes):
        super().__init__()
        self.conv1 = tgx.GCNConv(in_dim, 32)
        self.conv2 = tgx.GCNConv(32, num_classes)

    def forward(self, x, edge_index):
        return self.conv2(F.relu(self.conv1(x, edge_index)), edge_index)

def test_accuracy(model, x, edge_index, y, train, val, test):
    """Fit on train nodes, keep the weights with the best validation loss, score on test."""
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
    stopper, best = EarlyStopping(patience=20, mode="min"), None
    for _ in range(300):
        model.train()
        optimizer.zero_grad()
        F.cross_entropy(model(x, edge_index)[train], y[train]).backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            val_loss = F.cross_entropy(model(x, edge_index)[val], y[val]).item()
        stop = stopper.step(val_loss)
        if stopper.counter == 0:
            best = {k: v.clone() for k, v in model.state_dict().items()}
        if stop:
            break
    model.load_state_dict(best)
    model.eval()
    with torch.no_grad():
        predicted = model(x, edge_index).argmax(dim=1)
    return (predicted[test] == y[test]).float().mean().item()

def experiment(labels_follow, seeds=range(5)):
    scores = {}
    for seed in seeds:
        ei, num_nodes, community = mining.planted_partition_graph(
            num_communities=3, community_size=50, p_in=0.15, p_out=0.01, seed=seed)
        # Data and Node2Vec get their own seeds. Reusing the graph's seed would replay the
        # random numbers that placed its edges, so features or labels could encode them.
        rng = torch.Generator().manual_seed(seed + 1_000_003)
        y = community if labels_follow == "structure" else torch.randint(0, 3, (num_nodes,), generator=rng)
        x = torch.randn(num_nodes, 8, generator=rng)
        x[:, :3] += 1.5 * F.one_hot(y, 3)                  # noisy hint of the label
        train, val, test = node_train_val_test_split(num_nodes, 0.2, 0.2, 0.6, seed=seed)
        z = node2vec(ei, num_nodes, seed + 2_000_003)
        torch.manual_seed(seed)
        for name, model_class, inputs in [
            ("features only, no graph", LogisticRegression, x),
            ("Node2Vec only, no features", LogisticRegression, z),
            ("GCN on features", GCN, x),
            ("GCN on features + Node2Vec", GCN, torch.cat([x, z], dim=1)),
        ]:
            accuracy = test_accuracy(model_class(inputs.shape[1], 3), inputs, ei, y, train, val, test)
            scores.setdefault(name, []).append(accuracy)
    print(f"labels follow {labels_follow}")
    for name, values in scores.items():
        print(f"  {name:28s} mean test accuracy {sum(values) / len(values):.2f}")

experiment("structure")
experiment("features")

Output of the last two calls (five seeds each):

text
labels follow structure
  features only, no graph      mean test accuracy 0.61
  Node2Vec only, no features   mean test accuracy 0.98
  GCN on features              mean test accuracy 0.99
  GCN on features + Node2Vec   mean test accuracy 1.00
labels follow features
  features only, no graph      mean test accuracy 0.63
  Node2Vec only, no features   mean test accuracy 0.34
  GCN on features              mean test accuracy 0.40
  GCN on features + Node2Vec   mean test accuracy 0.34

Reading the result:

  • When labels follow the communities, anything that uses the graph does far better than the features alone. The Node2Vec baseline, which needs no features, is already close to the GCN.
  • When labels are unrelated to the graph, message passing averages in neighbours that carry no information about the node, and the GCN falls to not far above chance (one in three). The plain classifier on the node's own features wins.

This is one synthetic setup with a small graph, so do not read the numbers as a ranking of methods. The point is the procedure: run a no-graph baseline and a structure-only baseline before you attribute anything to message passing, and compare them on the same split.


Tensor-valued node features

When nodes hold feature maps rather than vectors, TGraphX's tensor layers pass messages without flattening them. Mining functions, which read only edge_index, work on the same graph.

python
from tgraphx import Graph, ConvMessagePassing

N, C, H, W = 50, 8, 6, 6
g = Graph(
    node_features=torch.randn(N, C, H, W),
    edge_index=torch.randint(0, N, (2, 200)),
    node_labels=torch.randint(0, 4, (N,)),
)

layer = ConvMessagePassing(in_shape=(C, H, W), out_shape=(16, H, W), dropout_prob=0.0)
print(tuple(layer(g.node_features, g.edge_index).shape))     # (50, 16, 6, 6)
print(tuple(mining.degree_centrality(g.edge_index, N).shape))  # (50,)

Key differences

Dimension Graph mining GNN message passing
Needs task labels No Usually (supervised); self-supervised training is possible
Randomness None for many measures; some methods are randomised Initialisation and training are random unless seeded
What you get A quantity with a definition A learned representation or prediction
New nodes or graphs Recompute Apply the trained weights, if features and edges are available
Uses node features Usually not Yes
Cost on large graphs Depends on the algorithm Often needs neighbour sampling
In TGraphX tgraphx.mining, tgraphx.algorithms tgraphx layers and models

Limitations

  • Mining features are no substitute for learning from features. If the signal lives in the node features, structural quantities alone will miss it, as the second experiment shows.
  • A GNN is not a graph algorithm. Its embeddings are fitted to a training objective, not to questions such as "is this edge a bridge?" or "does this subgraph contain a clique?".
  • tgraphx.mining is a set of small implementations, many of them plain Python loops with size caps, and 1.5.1 has known errors in a few of them (betweenness scaling, PageRank on graphs with sinks or isolated nodes, cross-graph WL features, mining.modularity). For serious graph analytics use a dedicated library: NetworkX for breadth on a single machine, or NetworKit, graph-tool, cuGraph or Spark GraphX when size matters.

Further reading

References

  • Gilmer, Schoenholz, Riley, Vinyals and Dahl (2017). Neural message passing for quantum chemistry. ICML.
  • Kipf and Welling (2016). Variational graph auto-encoders. NeurIPS Workshop on Bayesian Deep Learning.
  • Veličković, Fedus, Hamilton, Liò, Bengio and Hjelm (2019). Deep graph infomax. ICLR.
  • Xu, Hu, Leskovec and Jegelka (2019). How powerful are graph neural networks? ICLR.
  • Morris, Ritzert, Fey, Hamilton, Lenssen, Rattan and Grohe (2019). Weisfeiler and Leman go neural: higher-order graph neural networks. AAAI.