Code Architecture — Graph Attention Networks (GAT)

Overview

The notebook builds a two-layer GAT in NumPy with a hand-written backward pass, checks the gradients numerically, trains it with Adam on Zachary’s karate club graph with 6 labelled nodes, plots the attention weights, and compares it over 5 seeds with a GCN trained the same way. It runs on CPU in about a minute.

Section-by-Section Breakdown

1. Setup & Imports (cell 2)

  • Imports numpy, networkx, matplotlib and scikit-learn’s TSNE.
  • Saves figures as JPEG at dpi 80, registers the atexit hook that saves the executed notebook on Kaggle, and seeds NumPy with SEED = 42.

2. Graph Construction (cells 4–5)

  • nx.karate_club_graph(): 34 nodes, 78 edges. A = nx.to_numpy_array(G, weight=None) gives an unweighted 0/1 adjacency matrix.
  • Labels: 0 for the Mr. Hi faction and 1 for Officer (17 each). Features X = I (34 × 34 one-hot ids).
  • neighbors[i] lists the neighbours of node i plus i itself (mean size 5.59).

3. GAT Attention Layer (cells 7–8)

  • Activations: LeakyReLU (slope 0.2), ELU, softmax, and their gradients.
  • GATLayer(n_in, n_out, n_heads, activation, concat): per head a Glorot-initialised W (n_in × n_out) and an attention vector split into a_s and a_d, so e_ij = LeakyReLU(a_sᵀ W h_i + a_dᵀ W h_j).
  • forward: for each node, a softmax over its neighbours gives a row of the dense attention matrix alpha; the output is alpha @ (X W), then the activation. Heads are concatenated (concat=True) or averaged.
  • backward: gradients for W, a_s, a_d and the input, through the aggregation, the neighbourhood softmax and the LeakyReLU.

4. Two-Layer GAT Model (cell 10)

  • GATModel: layer 1 has 8 heads × 8 features (64, concatenated, ELU); layer 2 has 1 head with 2 outputs and softmax (Section 3.3 of the paper).
  • A test forward pass prints shapes (34, 64) and (34, 2).

5. Loss and Gradient Check (cells 12–13)

  • cross_entropy_loss and cross_entropy_grad use only the labelled nodes: the first 3 of each faction, nodes [0, 1, 2] and [9, 14, 15].
  • A finite-difference check on 5 random entries of each of the 27 parameter arrays (135 entries); the saved run prints a maximum difference of 2.35e-10.
  • An Adam class (default learning rate 0.005).

6. Training (cell 15)

  • train_gat(seed): Adam with learning rate 0.005, L2 5e-4 on the W matrices only, 150 full-batch epochs, no dropout. Prints loss and accuracy every 50 epochs.
  • Seed 42 result: loss 0.7219 → 0.0028; accuracy 1.0 on labelled, 0.9412 on all and 0.9286 on unlabelled nodes; misclassified [8, 30].

7. Training Visualisation (cell 17)

  • Loss curve, accuracy curves and the graph coloured by predicted faction (labelled nodes have a black border).

8. Attention Weights (cells 19–21)

  • Head 0 of layer 1 for nodes 0, 33, 16 and 7: edge widths proportional to attention on the graph, then bar charts of each node’s attention over its neighbours (green same faction, red other faction, orange self).

9. Multi-Head Comparison (cell 23)

  • Bar charts of node 0’s attention in heads 0 and 1 of layer 1.

10. Embeddings (cell 25)

  • t-SNE of the 64-dimensional hidden layer, coloured by true and by predicted faction.

11. GAT vs GCN (cells 27–29)

  • train_gcn(seed, hidden=16): a 2-layer GCN with the fixed matrix D̃^(−1/2)(A + I)D̃^(−1/2), Glorot initialisation, the same Adam, L2, epochs and labelled nodes.
  • Seed 42 on the 28 unlabelled nodes: GAT 0.9286, GCN 0.8571.
  • 11.1: both models retrained with seeds 0–4 (only the initial weights change). Saved run: GAT 0.9214 ± 0.0350, GCN 0.8571 ± 0.0000.

12. Summary (cell 30)

  • States what the saved run shows: the gradient check, the GAT results, the small GAT lead over GCN on this graph and its caveats, that the earlier version’s claim was not supported by its own numbers, and how the setup differs from the paper.

Differences from the Paper

Item Paper (Section 3.3) Notebook
Data Cora, Citeseer, Pubmed (transductive), PPI (inductive) Karate club, 34 nodes, one-hot features
Layer 1 8 heads × 8 features, ELU 8 heads × 8 features, ELU
Layer 2 1 head, softmax (8 heads on Pubmed) 1 head, softmax
Regularisation L2 0.0005, dropout 0.6 L2 0.0005 on W, no dropout
Optimiser Adam, lr 0.005 (0.01 Pubmed) Adam, lr 0.005
Stopping early stopping, patience 100 fixed 150 epochs
Evaluation mean test accuracy over 100 runs unlabelled-node accuracy over 5 seeds