AI Logic

Architectures

Graph Convolutional Network (GCN)

Updated:

Structure of GCN. The left side shows the overall flow from node features and the adjacency matrix through a two-layer GCN and softmax to a class for each node; the right side shows one node v summing its own and its neighbors' features, normalized by degree, to update itself

Background and Overview

A GCN (Graph Convolutional Network) is a neural network for graphs that stacks layers which average each node's features with those of its neighbors, normalized by degree, and apply a weight matrix shared by all nodes. Kipf and Welling proposed it in 2016 for "semi-supervised" node classification, where only some of the nodes have labels.

A graph is data made of "things" (nodes) and "connections" (edges), such as citations between papers, friendships on social networks, or atoms and bonds in a molecule. Image pixels sit on a regular grid, but graph nodes have varying numbers of neighbors and no fixed ordering. That makes it impossible to "slide a 3×3 window" the way convolution does in a CNN.

GCN solves this with a simple operation: gather features from neighboring nodes and use them to update each node's own features. In paper classification, for example, the network can directly exploit the fact that "papers that cite each other are often in the same field."

Before GCN, common approaches either spread labels along edges (label propagation) or learned node embeddings from random walks (DeepWalk and others). GCN uses node features and graph structure together in a single network, and it clearly outperformed these methods on citation network classification.

The ideas in GCN became the starting point for later models: GraphSAGE (samples neighborhoods so it also works on new nodes), GAT (learns per-neighbor weights with attention), and GIN (theoretically maximizes the range of graphs it can distinguish).

Theory: A First-Order Approximation of Graph Convolution

The GCN layer is built by approximating "convolution on a graph" until it becomes cheap to compute.

Graph notation

Let NN be the number of nodes, AA the adjacency matrix (Aij=1A_{ij} = 1 if nodes ii and jj are connected), and DD the degree matrix (Dii=∑jAijD_{ii} = \sum_j A_{ij}, i.e., the number of neighbors of each node). Let X∈RN×CX \in \mathbb{R}^{N \times C} be the matrix of node features.

Deriving the layer

  1. Start from spectral graph convolution: Convolution of a signal on a graph can be defined through the "graph Fourier transform," which uses the eigenvectors of the normalized graph Laplacian L=IN−D−1/2AD−1/2L = I_N - D^{-1/2} A D^{-1/2} (Bruna et al., 2014). This requires an eigendecomposition, which is far too expensive for large graphs.
  2. Approximate with Chebyshev polynomials: Defferrard et al. (2016) approximated the filter with a KK-th order polynomial in LL. This removes the need for an eigendecomposition, and each node only sees nodes up to KK hops away.
  3. Truncate at first order: GCN sets K=1K = 1, so a single layer only looks at direct neighbors. Distant nodes are reached by stacking layers. It further approximates the largest eigenvalue as λmax⁡≈2\lambda_{\max} \approx 2 and merges the two parameters into one, giving the filter θ(IN+D−1/2AD−1/2)\theta (I_N + D^{-1/2} A D^{-1/2}).
  4. Renormalize (renormalization trick): The eigenvalues of IN+D−1/2AD−1/2I_N + D^{-1/2} A D^{-1/2} lie in [0,2][0, 2], so applying it repeatedly makes values explode or vanish. GCN therefore first adds self-loops, A~=A+IN\tilde{A} = A + I_N, and uses their degrees D~ii=∑jA~ij\tilde{D}_{ii} = \sum_j \tilde{A}_{ij} to replace the operator with D~−1/2A~D~−1/2\tilde{D}^{-1/2} \tilde{A} \tilde{D}^{-1/2}.

The resulting GCN layer (Equation 2 in the paper) is:

H(l+1)=σ(D~−1/2A~D~−1/2H(l)W(l))H^{(l+1)} = \sigma\left(\tilde{D}^{-1/2} \tilde{A} \tilde{D}^{-1/2} H^{(l)} W^{(l)}\right)

H(l)∈RN×DH^{(l)} \in \mathbb{R}^{N \times D} holds the features of all nodes at layer ll (H(0)=XH^{(0)} = X), W(l)W^{(l)} is that layer's weight matrix, and σ\sigma is an activation function such as ReLU.

Viewed from a single node

Written per node vv (Equation 12 in Appendix A of the paper), the same formula becomes the following, where N(v)\mathcal{N}(v) is the set of vv's neighbors plus vv itself, and d~v\tilde{d}_v is the degree including the self-loop.

hv(l+1)=σ(∑u∈N(v)1d~vd~u hu(l)W(l))h_v^{(l+1)} = \sigma\left(\sum_{u \in \mathcal{N}(v)} \frac{1}{\sqrt{\tilde{d}_v \tilde{d}_u}}\, h_u^{(l)} W^{(l)}\right)

In other words, the layer "multiplies the features of the node and its neighbors by the same weight W(l)W^{(l)}, divides by degree, sums them, and passes the result through an activation function." Because the weights are shared across all nodes, the number of parameters does not depend on the number of nodes.

Architecture: A Two-Layer GCN and Semi-Supervised Training

The paper uses a two-layer GCN.

Forward pass (Equation 9 in the paper)

Z=softmax(A^ ReLU(A^XW(0))W(1)),A^=D~−1/2A~D~−1/2Z = \mathrm{softmax}\left(\hat{A}\ \mathrm{ReLU}\left(\hat{A} X W^{(0)}\right) W^{(1)}\right), \qquad \hat{A} = \tilde{D}^{-1/2} \tilde{A} \tilde{D}^{-1/2}
  1. Preprocessing: A^\hat{A} is computed once in advance. Since the graph structure does not change during training, every layer uses the same A^\hat{A}.
  2. First layer: Compute A^XW(0)\hat{A} X W^{(0)} and apply ReLU. W(0)∈RC×HW^{(0)} \in \mathbb{R}^{C \times H} maps the CC input dimensions to HH hidden dimensions.
  3. Second layer: Multiply by A^\hat{A} again and map to the number of classes FF with W(1)∈RH×FW^{(1)} \in \mathbb{R}^{H \times F}.
  4. Output: Apply softmax per node to get class probabilities.

Training (Equation 10 in the paper)

The loss is the cross-entropy computed only over the set of labeled nodes YL\mathcal{Y}_L.

L=−∑l∈YL∑f=1FYlfln⁡Zlf\mathcal{L} = -\sum_{l \in \mathcal{Y}_L} \sum_{f=1}^{F} Y_{lf} \ln Z_{lf}

Unlabeled nodes do not contribute to the loss, but they still take part in passing features through A^\hat{A}. As a result, the features of unlabeled nodes also help predict the labeled ones.

For the citation network experiments, the paper trained with the following settings.

ItemValue
Hidden dimension HH16
Dropout rate0.5 (all layers)
L2 regularization (Weight Decay)5×10−45 \times 10^{-4} (first layer only)
OptimizerAdam, learning rate 0.01
EpochsUp to 200; stop if the validation loss does not decrease for 10 consecutive epochs (Early Stopping)
Weight initializationXavier (Glorot) initialization
Mini-batchesNot used (one gradient descent step on the full graph each time)

A^\hat{A} is a sparse matrix with mostly zero entries, so A^X\hat{A} X can be computed as a sparse-dense matrix product. The cost scales with the number of edges ∣E∣|\mathcal{E}| (O(∣E∣CF)O(|\mathcal{E}| C F) per layer in the paper), and there is no need to build a dense N×NN \times N matrix.

How It Works and Why It Is Effective

GCN works well for three main reasons.

  • It fits graphs where similar nodes connect: In graphs like citation networks, where connected nodes tend to share a class, the average of neighbors' features is a less noisy signal than a node's own features alone. Even for a document with too few words to reveal its field, the field can be inferred from the words of documents it cites or is cited by.
  • Degree normalization makes it robust to neighbor count: A node with 100 neighbors and a node with only 2 would produce values of very different magnitudes under a plain sum. Dividing by 1/d~vd~u1/\sqrt{\tilde{d}_v \tilde{d}_u} keeps magnitudes comparable and prevents divergence as layers are stacked. The self-loop is added so that a node's own features are included in the average.
  • More layers reach farther: Each layer brings in information from one more hop, so two layers mix information from up to 2 hops away, and KK layers from up to KK hops away.

Relation to the Weisfeiler-Lehman procedure

Appendix A of the paper explains that GCN can be viewed as a differentiable version of the one-dimensional Weisfeiler-Lehman (WL) procedure used for graph isomorphism testing. The WL procedure repeatedly recolors each node with a new color determined by "its own color and the collection of its neighbors' colors." GCN replaces the hash function in this recoloring with a weighted sum, a weight matrix WW, and an activation function.

This view implies that even a GCN with random, untrained weights can extract features that reflect graph structure. In the paper, simply passing the 34-member karate club graph through a three-layer GCN with random weights produced a 2D embedding where the groups formed clusters, close to the embedding that DeepWalk learns from random walks (Figure 3 in the paper).

Experimental Results

Node classification on citation networks and a knowledge graph (Table 2 in the paper; accuracy in %, with time to convergence in parentheses)

The paper used three citation networks (Citeseer, Cora, Pubmed; nodes are documents, edges are citations, features indicate word presence) and NELL, built from a knowledge graph. For the citation networks, only 20 nodes per class were labeled for training, and evaluation used 1,000 nodes.

MethodCiteseerCoraPubmedNELL
Label propagation (LP)45.368.063.026.5
DeepWalk43.267.265.358.1
ICA69.175.173.923.1
Planetoid64.7 (26 s)75.7 (13 s)77.2 (25 s)61.9 (185 s)
GCN70.3 (7 s)81.5 (4 s)79.0 (38 s)66.0 (48 s)

GCN achieved the highest accuracy on all four datasets. Compared with Planetoid, whose training time was also measured, GCN also finished training faster on every dataset except Pubmed.

Comparison of layer formulas (Table 3 in the paper; accuracy in %)

These results compare the formulas from each stage of the approximation in the theory section under the same conditions.

Layer formulaCiteseerCoraPubmed
Chebyshev polynomial (K=3K = 3)69.879.574.4
Chebyshev polynomial (K=2K = 2)69.681.273.8
First-order model (2 parameters)68.380.077.5
Single parameter69.379.277.4
Renormalized (GCN)70.381.579.0
Neighbor term only (no self-loop)68.780.577.8
MLP (no graph)46.555.171.4

The GCN formula, which goes furthest in the approximation and has the fewest parameters, achieved the highest accuracy. The gap to an MLP that ignores the graph exceeds 26 points on Cora, showing how much the graph structure helps.

Number of layers (Appendix B of the paper)

Varying the depth from 1 to 10 layers showed that 2 or 3 layers worked best on the citation networks. Beyond 7 layers, training became difficult unless residual connections (the same additive shortcut as in ResNet) were added between layers.

Practical Considerations

Keep the following points in mind when using GCN.

  • Do not go too deep: Each additional layer widens the range each node sees (up to KK hops) and adds parameters, making overfitting more likely. In the paper, training became difficult beyond 7 layers without residual connections. Start with 2–3 layers, and add residual connections if going deeper.
  • The whole graph must fit in memory: The original GCN computes over the entire graph every step. Memory grows with the number of edges, so graphs with millions of nodes or more may not fit on a GPU. In that case, use methods such as GraphSAGE that sample neighborhoods and train with mini-batches.
  • No edge directions or edge features: The original GCN assumes an undirected (symmetric) adjacency matrix. Directed or typed edges require workarounds, such as converting edges into nodes to form a bipartite graph, as in the paper's NELL experiment.
  • Self and neighbors are weighted equally: In A~=A+IN\tilde{A} = A + I_N, the self-loop and the edges to neighbors carry the same weight. The paper itself notes that for some data it may be better to change the self weight, as in A~=A+λIN\tilde{A} = A + \lambda I_N.
  • Where to get it in PyTorch: PyTorch itself has no GCN layer. It can be written in a few lines, as in the implementation example below, or you can use GCNConv from PyTorch Geometric or GraphConv from DGL.

The original GCN is designed for the transductive setting, where it classifies nodes of the graph seen during training. Because A^\hat{A} is built from the whole graph, adding nodes after training or applying the model to a different graph changes the normalization values and neighborhoods. To handle new nodes or other graphs, also consider GraphSAGE or GAT, which were evaluated in that setting.

Comparison with Other Methods

Comparing four representative graph neural networks from the same angle, "how they gather features from neighboring nodes," gives the following.

MethodHow neighbor features are aggregatedPer-neighbor weightNeighbors usedMain use case
GCNDegree-normalized sum (including self)Determined by degree (not learned)All neighborsNode classification within one graph
GraphSAGEAggregate with mean, LSTM, or pooling, then concatenate with own featuresDepends on the aggregatorA fixed number, sampledLarge graphs that include new nodes
GATWeighted sum using attention weightsLearned from featuresAll neighborsNode classification (also on new graphs)
GINScale self by (1+ϵ)(1 + \epsilon), add neighbor features, pass through an MLPAll 1 (plain sum)All neighborsWhole-graph classification

Rough guidelines for choosing:

  • Classifying nodes with few labels within a single graph: Try GCN first. Its formula is simple and fast, and it is a strong baseline on data like citation networks.
  • The graph is large, or new nodes appear after training: GraphSAGE, which samples neighborhoods and trains with mini-batches, is a good fit.
  • Neighbors likely differ in importance: Try GAT, which learns a weight for each neighbor.
  • Distinguishing the shapes of whole graphs, as with molecules: GIN is a good fit, since it can distinguish structures that averaging cannot.

PyTorch example

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


# A small implementation following Equations 2 and 9 of the paper (PyTorch itself has no GCN layer)


def normalize_adjacency(edge_index, num_nodes):
  # Build  = D̃^{-1/2} (A + I) D̃^{-1/2} as a sparse matrix. edge_index is [2, E] (include both directions for undirected edges)
  self_loops = torch.arange(num_nodes).repeat(2, 1)
  index = torch.cat([edge_index, self_loops], dim=1)            # add self-loops (Ã = A + I)
  value = torch.ones(index.size(1))
  deg = torch.zeros(num_nodes).scatter_add_(0, index[0], value)  # D̃_ii = Σ_j Ã_ij
  d_inv_sqrt = deg.pow(-0.5)
  value = d_inv_sqrt[index[0]] * value * d_inv_sqrt[index[1]]    # 1 / √(d̃_i d̃_j)
  return torch.sparse_coo_tensor(index, value, (num_nodes, num_nodes)).coalesce()


class GCNLayer(nn.Module):
  def __init__(self, in_dim, out_dim):
    super().__init__()
    self.linear = nn.Linear(in_dim, out_dim, bias=False)  # W (shared by all nodes)
    nn.init.xavier_uniform_(self.linear.weight)           # the paper uses Glorot initialization

  def forward(self, x, a_hat):
    # Â H W: apply W first, then gather neighbor features with a sparse matrix product
    return torch.sparse.mm(a_hat, self.linear(x))


class GCN(nn.Module):
  def __init__(self, in_dim, hidden_dim=16, num_classes=7, dropout=0.5):
    super().__init__()
    self.gc1 = GCNLayer(in_dim, hidden_dim)
    self.gc2 = GCNLayer(hidden_dim, num_classes)
    self.dropout = dropout

  def forward(self, x, a_hat):
    # dropout is active only under model.train() and does nothing under model.eval()
    x = F.dropout(x, self.dropout, self.training)
    x = F.relu(self.gc1(x, a_hat))
    x = F.dropout(x, self.dropout, self.training)
    return self.gc2(x, a_hat)  # softmax is computed inside the loss function


# Usage (an example the same size as Cora; in practice, load X, edges, and labels from the dataset)
num_nodes, in_dim, num_classes = 2708, 1433, 7
x = torch.rand(num_nodes, in_dim)
edge_index = torch.randint(0, num_nodes, (2, 10556))
labels = torch.randint(0, num_classes, (num_nodes,))
train_mask = torch.zeros(num_nodes, dtype=torch.bool)
train_mask[:140] = True  # 20 per class × 7 classes

a_hat = normalize_adjacency(edge_index, num_nodes)
model = GCN(in_dim, num_classes=num_classes)
optimizer = torch.optim.Adam([
  {"params": model.gc1.parameters(), "weight_decay": 5e-4},  # L2 regularization on the first layer only
  {"params": model.gc2.parameters(), "weight_decay": 0.0},
], lr=0.01)

for epoch in range(200):
  model.train()
  optimizer.zero_grad()
  out = model(x, a_hat)                                    # compute all nodes at once
  loss = F.cross_entropy(out[train_mask], labels[train_mask])  # loss on labeled nodes only
  loss.backward()
  optimizer.step()

model.eval()
with torch.no_grad():
  pred = model(x, a_hat).argmax(dim=1)

FAQ

Q. What does GCN's "convolution" share with convolution in a CNN, and how does it differ?
A.

What they share is that both look only at nearby values and reuse the same weights at every location. The difference is that a CNN has a separate weight for each position in its window, while GCN, because neighbors have no order, applies the same weight WW to every neighbor and sums the results with degree normalization. This lets GCN use the same formula for nodes with different numbers or orderings of neighbors.

Q. Does making the network deeper improve accuracy?
A.

Not necessarily. In the paper's citation network experiments, 2–3 layers worked best, and beyond 7 layers training became difficult without residual connections. The paper attributes this to the range each node sees widening with every layer and to the growing number of parameters making overfitting more likely.

Q. Can a trained GCN classify new nodes?
A.

The original GCN is a method for the transductive setting, where A^\hat{A} is built from the whole graph at training time. The formula can technically be computed for new nodes, but the normalization values and neighborhoods change, and the paper did not evaluate performance in that setting. For new nodes or different graphs, consider GraphSAGE or GAT, which were evaluated in that setting.

References

  1. Kipf, T. N., & Welling, M. (2017). Semi-Supervised Classification with Graph Convolutional Networks. ICLR 2017. arXiv:1609.02907.
  2. tkipf/gcn (the authors' TensorFlow implementation).
  3. Defferrard, M., Bresson, X., & Vandergheynst, P. (2016). Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering. NIPS 2016. arXiv:1606.09375.
  4. Bruna, J., Zaremba, W., Szlam, A., & LeCun, Y. (2014). Spectral Networks and Locally Connected Networks on Graphs. ICLR 2014. arXiv:1312.6203.
  5. Hamilton, W. L., Ying, R., & Leskovec, J. (2017). Inductive Representation Learning on Large Graphs. NIPS 2017. arXiv:1706.02216.
  6. Xu, K., Hu, W., Leskovec, J., & Jegelka, S. (2019). How Powerful are Graph Neural Networks? ICLR 2019. arXiv:1810.00826.