TGraphX › Insights › Graph Convolutional Networks (GCN): Normalised Adjacency by Hand
← Back to Insights

Graph Convolutional Networks (GCN): Normalised Adjacency by Hand

Topic: GNN architectures and learning tasks

A graph convolutional network (GCN) is a neural network for graph-structured data. Each of its layers replaces every node's feature vector with a weighted sum of its own vector and its neighbours' vectors, and applies one shared linear map. The weights in that sum are not learned; they come from node degrees:

text
H' = D^-1/2 (A + I) D^-1/2 H W^T + b

h'_j = W ( Σ_{i ∈ N(j) ∪ {j}}  h_i / sqrt(d_i · d_j) ) + b

H is [N, d] (one row per node), A is the N × N adjacency matrix, I adds one self-loop per node, D is the diagonal degree matrix of A + I, W is [d', d] and b has d' entries. N(j) is the set of nodes with an edge into j, and d_j is the degree of j counting its self-loop. A nonlinearity such as ReLU usually follows between layers.

This page builds the matrix for a four-node graph, computes one layer by hand, reproduces the numbers three ways in PyTorch, and then lists the cases where the formula and an implementation can disagree with your expectation. Examples tested with TGraphX 1.5.1 on CPU; the code blocks run in order.

Index convention

Edges are stored in edge_index, a [2, E] integer tensor. Row 0 holds source nodes i, row 1 holds destination nodes j, and information flows from i to j. The matching matrix entry is A[j, i] = 1, so that row j of the product A H collects the vectors arriving at j. For an undirected graph both directions are listed, A is symmetric and the order of the indices does not matter. It starts to matter for directed graphs, discussed below.

A four-node graph

Take the path 0 - 1 - 2 - 3 and add the chord 0 - 2. All edges are undirected.

text
    0 ----- 1
      \     |
       \    |
         \  |
            2 ----- 3

With the self-loop counted, the degrees are d = (3, 3, 4, 2): node 0 has neighbours 1 and 2 plus itself, node 2 has neighbours 0, 1 and 3 plus itself, and so on.

The normalised matrix, written  below, has entry Â[j, i] = 1 / sqrt(d_j · d_i) wherever A + I has a one:

node 0 node 1 node 2 node 3
row 0 1/3 1/3 1/√12 ≈ 0.289 0
row 1 1/3 1/3 1/√12 ≈ 0.289 0
row 2 1/√12 ≈ 0.289 1/√12 ≈ 0.289 1/4 1/√8 ≈ 0.354
row 3 0 0 1/√8 ≈ 0.354 1/2

Three things are visible before any learning happens. The matrix is symmetric. A weight shrinks as the degree of either endpoint grows: node 0 weighs its edge to the well-connected node 2 at 0.289 and its edge to node 1 at 1/3. And the rows do not sum to one: they sum to about 0.955, 0.955, 1.181 and 0.854. A GCN layer is therefore not a plain average of the neighbourhood.

GCN weights on the four node example graph

0123

Weights used to update node 2 (degree with self-loop d̃ = 4). Sum of GCN weights: 1.1809; sum of attention coefficients: 1.0000.

from 0, d̃ = 3

GCN 1/√(4·3) = 0.2887

attention α = 0.2500 (score e = 0)

from 1, d̃ = 3

GCN 1/√(4·3) = 0.2887

attention α = 0.2500 (score e = 0)

from 2 (itself), d̃ = 4

GCN 1/√(4·4) = 0.2500

attention α = 0.2500 (score e = 0)

from 3, d̃ = 2

GCN 1/√(4·2) = 0.3536

attention α = 0.2500 (score e = 0)

GCN, exact: D̃^(−1/2) (A + I) D̃^(−1/2), self-loops added
0123
00.3330.3330.2890
10.3330.3330.2890
20.2890.2890.2500.354
3000.3540.500

Target 2: GCN weights sum to 1.1809; attention coefficients sum to 1.0000 (α from 0 0.2500, 1 0.2500, 2 0.2500, 3 0.2500).

Pick a target node. The GCN weights follow from the degrees alone; attention coefficients depend on scores you set and are only an illustration. GCN weights are exact for this graph. Attention is illustrative: the scores e are chosen by hand, not learned; α is their softmax over the neighbourhood and the node itself. A GAT computes e from node features with learned parameters.

One layer by hand

Give each node a two-dimensional feature:

text
h_0 = (3, 0)    h_1 = (0, 3)    h_2 = (4, 4)    h_3 = (2, 0)

First aggregate with the rows of Â. For node 0:

text
a_0 = 1/3·(3,0) + 1/3·(0,3) + 0.28868·(4,4)
    = (1, 0) + (0, 1) + (1.1547, 1.1547)
    = (2.1547, 2.1547)

For node 2, which sees all four nodes:

text
a_2 = 0.28868·(3,0) + 0.28868·(0,3) + 0.25·(4,4) + 0.35355·(2,0)
    = (0.8660, 0) + (0, 0.8660) + (1, 1) + (0.7071, 0)
    = (2.5731, 1.8660)

Node 3 gets 0.35355·(4,4) + 0.5·(2,0) = (2.4142, 1.4142). Node 1 has the same row as node 0, so a_1 = a_0.

Now apply the shared linear map. Choose, purely for readable arithmetic,

text
W = [[1,  1],        b = (0, 0.5)
     [1, -1]]

so each node's output is (a_x + a_y, a_x - a_y + 0.5):

node aggregate output h'
0 (2.1547, 2.1547) (4.3094, 0.5000)
1 (2.1547, 2.1547) (4.3094, 0.5000)
2 (2.5731, 1.8660) (4.4392, 1.2071)
3 (2.4142, 1.4142) (3.8284, 1.5000)

Nodes 0 and 1 started with different features, (3, 0) and (0, 3), and end with identical outputs. This is exact, not a coincidence of the numbers. Both nodes have the same closed neighbourhood {0, 1, 2} and the same degree, so their rows of  are equal, and no choice of W or b can separate them afterwards. Whenever two nodes have the same closed neighbourhood in an unweighted undirected graph, one GCN layer maps them to the same vector, and every later layer keeps them equal. If your labels differ between such twins, a plain GCN cannot fit them; a separate path for the node's own features (a skip connection or a self weight) can.

The same numbers in PyTorch

Dense matrix form

python
import torch
import tgraphx as tgx

# Row 0: sources, row 1: destinations. Both directions of every undirected edge.
edge_index = torch.tensor([[0, 1, 1, 2, 2, 3, 0, 2],
                           [1, 0, 2, 1, 3, 2, 2, 0]])
x = torch.tensor([[3.0, 0.0], [0.0, 3.0], [4.0, 4.0], [2.0, 0.0]])   # [N, d]
N = x.size(0)

A = torch.zeros(N, N)
A[edge_index[1], edge_index[0]] = 1.0            # A[destination, source]
A_loop = A + torch.eye(N)
degree = A_loop.sum(dim=1)                       # incoming weight, loop included
D_inv_sqrt = torch.diag(degree.pow(-0.5))
A_hat = D_inv_sqrt @ A_loop @ D_inv_sqrt

W = torch.tensor([[1.0, 1.0], [1.0, -1.0]])      # [d_out, d_in]
b = torch.tensor([0.0, 0.5])
out_dense = A_hat @ x @ W.T + b

print(degree.tolist())                           # [3.0, 3.0, 4.0, 2.0]
print([round(v, 4) for v in A_hat.sum(dim=1).tolist()])
# [0.9553, 0.9553, 1.1809, 0.8536]
print([[round(v, 4) for v in row] for row in out_dense.tolist()])
# [[4.3094, 0.5], [4.3094, 0.5], [4.4392, 1.2071], [3.8284, 1.5]]

Edge list form

A dense N × N matrix is fine for four nodes and hopeless for large sparse graphs. The same operation over the edge list gathers each source vector, scales it, and adds it into the destination row with index_add_:

python
def gcn_propagate(x, edge_index):
    """D^-1/2 (A + I) D^-1/2 x for x of shape [N, ...]; no weights."""
    n = x.size(0)
    loops = torch.arange(n, device=x.device)
    src = torch.cat([edge_index[0], loops])
    dst = torch.cat([edge_index[1], loops])
    deg = torch.zeros(n, dtype=x.dtype, device=x.device)
    deg.index_add_(0, dst, torch.ones(dst.numel(), dtype=x.dtype, device=x.device))
    norm = (deg[src] * deg[dst]).rsqrt()
    messages = x[src] * norm.view(-1, *([1] * (x.dim() - 1)))
    return torch.zeros_like(x).index_add_(0, dst, messages)

out_sparse = gcn_propagate(x, edge_index) @ W.T + b
assert torch.allclose(out_sparse, out_dense)

The message buffer has one row per edge plus one per node, so memory grows with E + N instead of N².

tgraphx.GCNConv

TGraphX ships the layer as GCNConv for vector features. It appends the self-loops itself, so you pass the graph without them. Copying W and b into it gives the same output:

python
conv = tgx.GCNConv(2, 2)
with torch.no_grad():
    conv.lin.weight.copy_(W)
    conv.lin.bias.copy_(b)
    assert torch.allclose(conv(x, edge_index), out_dense)
print(tgx.count_parameters(conv))                # 6

The parameter count is d·d' + d' and does not depend on the number of nodes or edges. That is why a trained GCN can be applied to a different graph with the same feature dimension: only  is rebuilt.

Where the formula comes from

Kipf and Welling started from spectral filters, functions applied to the eigenvalues of the normalised Laplacian L = I - D^-1/2 A D^-1/2. Computing an eigendecomposition is expensive, so earlier work approximated the filter by a polynomial in L, which only involves neighbours up to the polynomial degree. Their steps were:

  1. Keep only the first-order polynomial and approximate the largest eigenvalue of L by 2. This gives two free parameters, one for the node itself and one for D^-1/2 A D^-1/2.
  2. Tie them to a single parameter, leaving the operator I + D^-1/2 A D^-1/2.
  3. Its eigenvalues lie in [0, 2], so repeating it layer after layer can make values explode or vanish. Replace it by D̃^-1/2 (A + I) D̃^-1/2, where the degrees now include the self-loop. The paper calls this the renormalisation trick.

The last step is a change of operator, not an algebraic identity. Its eigenvalues lie in (-1, 1], and the largest is 1 with an eigenvector proportional to sqrt(d). On the example graph:

python
eigenvalues = torch.linalg.eigvalsh(A_hat)
print([round(v, 4) + 0.0 for v in eigenvalues.tolist()])
# [-0.1477, 0.0, 0.5643, 1.0]
v = degree.sqrt()
assert torch.allclose(A_hat @ v, v)

The zero eigenvalue is the twin pair of nodes 0 and 1 again: their difference is annihilated by Â.

Two consequences matter in practice. Applying  many times without weights drives the features towards multiples of sqrt(d) on each connected component, which is the linear core of over-smoothing. And a stack of k GCN layers with the nonlinearities removed collapses to Â^k H Θ, which is the model Wu and co-authors call Simple Graph Convolution and analyse as a fixed low-pass filter. Graph spectral analysis with TGraphX shows the frequency response of this filter.

Why symmetric normalisation instead of a mean?

A row-normalised operator D^-1 (A + I) divides by the receiver's degree only, so each output is a true average. The symmetric form divides by sqrt(d_i · d_j), so it also discounts a sender that has many connections. Which is better for a task is an empirical question. What you can say from the formulas:

Operator Weight of edge i → j Sum over a row Symmetric matrix
A + I (plain sum) 1 d_j yes, if A is
D^-1 (A + I) (mean) 1 / d_j 1 generally no
D^-1/2 (A + I) D^-1/2 (GCN) 1 / sqrt(d_i · d_j) not fixed yes, if A is

A two-layer GCN for node classification

The original paper's node classifier is two layers: Z = softmax( Â ReLU( Â X W0 ) W1 ). The block below trains it, and an MLP of the same widths without edges, on a synthetic graph with two communities. Edges are dense inside a community (probability 0.08) and sparse between communities (0.01), and a single noisy feature column carries a weak class signal. The task is built to favour graph averaging, so the result shows the mechanism and says nothing about real datasets.

python
import torch.nn as nn
import torch.nn.functional as F

def make_data(seed, n_per_class=100):
    graph_rng = torch.Generator().manual_seed(seed)
    y = torch.arange(2).repeat_interleave(n_per_class)
    n = y.numel()
    p = torch.where(y[:, None] == y[None, :], 0.08, 0.01)
    upper = torch.triu(torch.rand(n, n, generator=graph_rng) < p, diagonal=1)
    edges = (upper | upper.T).nonzero().t()

    feature_rng = torch.Generator().manual_seed(10_000 + seed)   # not the graph seed
    features = torch.randn(n, 16, generator=feature_rng)
    features[:, 0] += 0.7 * (2 * y - 1)
    order = torch.randperm(n, generator=feature_rng)
    return features, edges, y, order[:20], order[20:60], order[60:]

class TwoLayer(nn.Module):
    def __init__(self, use_graph):
        super().__init__()
        self.use_graph = use_graph
        make = tgx.GCNConv if use_graph else nn.Linear
        self.first, self.second = make(16, 16), make(16, 2)

    def forward(self, x, edges):
        args = (edges,) if self.use_graph else ()
        return self.second(F.relu(self.first(x, *args)), *args)

def run(use_graph, seed):
    features, edges, y, train, val, test = make_data(seed)
    torch.manual_seed(seed)
    model = TwoLayer(use_graph)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
    best_val, test_at_best = float("inf"), None
    for _ in range(200):
        model.train()
        optimizer.zero_grad()
        F.cross_entropy(model(features, edges)[train], y[train]).backward()
        optimizer.step()
        model.eval()
        with torch.no_grad():
            logits = model(features, edges)
            val_loss = F.cross_entropy(logits[val], y[val]).item()
        if val_loss < best_val:              # select the epoch on validation only
            best_val = val_loss
            test_at_best = (logits.argmax(1)[test] == y[test]).float().mean().item()
    return test_at_best

for name, use_graph in [("MLP", False), ("GCN", True)]:
    scores = torch.tensor([run(use_graph, seed) for seed in range(5)])
    print(f"{name}: mean {scores.mean().item():.3f}  std {scores.std().item():.3f}")

Output of this run (5 seeds, each with its own graph, features and split; 20 training, 40 validation and 140 test nodes):

text
MLP: mean 0.564  std 0.076
GCN: mean 0.973  std 0.013

This is a transductive setting: the model sees the features and edges of all nodes, and only the labels of the training nodes enter the loss. State that when you report such numbers. Exact decimals can differ across PyTorch versions and hardware. Always keep the edge-free baseline: if the MLP matches the GCN on your data, the graph is not contributing.

Where implementations differ from the formula

Directed graphs

The GCN derivation assumes an undirected graph, and the paper says its framework is limited to undirected graphs. If you pass a directed edge_index, GCNConv still runs. Its degree vector is the in-degree (plus one for the loop) and is used for both ends of an edge, so the sender's weight depends on how many edges point into it, not on how many it sends. The result is neither row nor column normalised. Decide explicitly: symmetrise the edges first, or use a layer designed around direction.

python
directed = torch.tensor([[0, 0, 0],       # node 0 sends to 1, 2, 3
                         [1, 2, 3]])
ones = torch.ones(4, 1)
print([round(v, 4) for v in gcn_propagate(ones, directed).flatten().tolist()])
# [1.0, 1.2071, 1.2071, 1.2071]

Node 0 sends three edges, yet its degree is 1 because nothing points into it. Each receiver gets 1/sqrt(1·2) ≈ 0.707 from it plus 1/2 from its own loop.

Self-loops that are already there

In TGraphX 1.5.1, GCNConv appends a loop for every node without checking whether edge_index already contains one. A graph that already has loops gets them counted twice, which changes both the degrees and the weights:

python
loops = torch.arange(N).repeat(2, 1)
with torch.no_grad():
    doubled = conv(x, torch.cat([edge_index, loops], dim=1))
print(torch.allclose(doubled, out_dense))        # False

Remove existing loops before the layer, for example with keep = edge_index[0] != edge_index[1]. Other libraries make other choices: PyTorch Geometric 2.8.1 GCNConv adds only the missing loops, so the same input can give different outputs in the two libraries.

add_self_loops=False is right only if your edge_index already holds the loops. Without them, a node with no incoming edge has degree zero, which the layer clamps to 1e-12; in a directed graph its outgoing weights become about a million.

Isolated nodes, duplicates and weights

  • An isolated node only has its self-loop, so its output is W h_j + b. The layer degrades to a linear model for that node.
  • A repeated edge is counted twice, in the sum and in the degree. Coalesce edges if repeats are an artefact.
  • edge_weight of shape [E] replaces the ones in A. The weights also enter the degrees, and each added self-loop has weight 1. Negative weights can make a degree zero or negative; the square root normalisation is not meaningful then.

Tensor-valued node features

GCNConv accepts [N, d] only and raises ValueError for [N, C, H, W]. TGraphX 1.5.1 has no tensor GCN layer, but the propagation acts on the node axis alone, so gcn_propagate above already handles any trailing shape. Following it with a 1×1 convolution applies one shared W at every position:

python
generator = torch.Generator().manual_seed(1)
maps = torch.randn(4, 2, 3, 3, generator=generator)       # [N, C, H, W]
mix = nn.Conv2d(2, 2, kernel_size=1)
with torch.no_grad():
    mix.weight.copy_(W.view(2, 2, 1, 1))
    mix.bias.copy_(b)
    tensor_out = mix(gcn_propagate(maps, edge_index))
    for row in range(3):
        for col in range(3):
            assert torch.allclose(tensor_out[:, :, row, col],
                                  conv(maps[:, :, row, col], edge_index), atol=1e-5)

try:
    conv(maps, edge_index)
except ValueError as err:
    print("GCNConv:", err)

Each pixel position behaves like its own vector GCN. Mixing positions needs larger kernels or a node encoder, which is a different model.

Limits of the layer

  • Fixed weights. The layer cannot learn that one neighbour matters more than another. Graph attention versus graph convolution compares the two choices.
  • Expressiveness. Like other message-passing layers it cannot tell apart everything that differs structurally, and its normalised sum can lose neighbourhood size. Graph Isomorphism Networks discusses that bound.
  • Depth. k layers reach k hops; deeper stacks run into over-smoothing.
  • Full-graph training. The two-layer example computes all nodes at every step. Large graphs need sampling or partitioning, and sampled subgraphs have different degrees, so their  differs from the full-graph one.

For the general message, aggregate and update template behind the index_add_ code, see message passing from scratch in PyTorch.

To put a CNN in front of layers like this one, see how to combine a CNN and a GNN in PyTorch.

Summary

A GCN layer is  H W^T + b, with  = D̃^-1/2 (A + I) D̃^-1/2. The matrix is built from the graph alone, the parameters are one shared linear map, and the edge-list form is a gather, a scale and an index_add_. Check three things in any implementation you use: which degree it normalises by on directed graphs, what it does with existing self-loops, and which feature ranks it accepts.

References