Buckets:
Graph Neural Networks Notebook Guide
π Notebook: 02_Graph_Neural_Networks.ipynb
Overview
This comprehensive notebook explores Graph Neural Networks (GNNs) applied to Knowledge Graphs, demonstrating cutting-edge architectures for multi-relational reasoning.
What's Included
1. Introduction and Setup β
- Import all necessary libraries (PyTorch, PyTorch Geometric, etc.)
- Configure device (CPU/GPU)
- Set random seeds for reproducibility
- Import custom KG modules
2. Knowledge Graph Creation β
- Create a sample knowledge graph with entities and relations
- Convert to PyTorch Geometric Data format
- Display graph statistics
- Visualize graph structure
3. GCN: Graph Convolutional Networks β
Theory: GCN aggregates information from neighbors using layer-wise propagation
Formula:
h_v^{(l+1)} = Ο(Ξ£_{u β N(v)} 1/β(|N(u)||N(v)|) W^{(l)} h_u^{(l)})
Implementation:
- Initialize GCN with 2 layers
- Forward pass through the network
- Output entity embeddings
- Analyze embedding statistics
Strengths:
- β Simple and efficient
- β Captures multi-hop neighborhood
- β Fast training
Use Cases: Homogeneous graphs, citation networks, social networks
4. GAT: Graph Attention Networks β
Theory: GAT learns attention weights to determine neighbor importance
Formula:
Ξ±_vu = exp(LeakyReLU(a^T [W h_v || W h_u])) / Ξ£_k exp(...)
h_v^{(l+1)} = Ο(Ξ£_{u β N(v)} Ξ±_vu W^{(l)} h_u^{(l)})
Implementation:
- Multi-head attention mechanism (4 heads)
- Attention weight visualization
- Distribution analysis
Features:
- β Learns edge importance
- β Multi-head attention for robustness
- β Interpretable through attention weights
- β Better handles varying neighbor importance
Visualization:
- Histogram of attention weights
- Top-k important edges
- Attention distribution per layer
Use Cases: Heterogeneous graphs, recommendation systems, molecular graphs
5. GraphSAGE β
Theory: Sample and aggregate features from node neighborhoods
Formula:
h_v^{(l+1)} = Ο(W^{(l)} Β· CONCAT(h_v^{(l)}, AGG({h_u^{(l)}, βu β N(v)})))
Aggregation Functions:
- Mean: Average neighbor features
- Max: Element-wise maximum
- LSTM: Sequential aggregation
Implementation:
- Mean aggregator
- 2-layer architecture
- Batch normalization
Strengths:
- β Scalable to large graphs through sampling
- β Inductive learning (generalizes to unseen nodes)
- β Multiple aggregation strategies
- β Efficient mini-batch training
Use Cases: Large-scale graphs, Pinterest recommendations, protein interactions
6. R-GCN: Relational Graph Convolutional Networks β
Theory: Specifically designed for multi-relational graphs like Knowledge Graphs
Formula:
h_v^{(l+1)} = Ο(Ξ£_{rβR} Ξ£_{uβN_v^r} 1/|N_v^r| W_r^{(l)} h_u^{(l)} + W_0^{(l)} h_v^{(l)})
Basis Decomposition:
W_r = Ξ£_{b=1}^B a_rb V_b
Reduces parameters from O(num_relations Γ dΒ²) to O(num_bases Γ dΒ²)
Implementation:
- Relation-specific weight matrices
- Basis decomposition for parameter efficiency
- Handles edge types explicitly
Key Features:
- β Handles multiple relation types
- β Basis decomposition for scalability
- β Perfect for Knowledge Graphs
- β Captures relational patterns
Analysis:
- Relation-specific statistics
- Edge type distribution
- Embedding quality per relation
Use Cases: Knowledge graphs, biomedical networks, semantic web
7. Training Pipeline β
Data Preparation:
- Create positive triples from KG
- Generate negative samples (corrupted head/tail)
- 80/20 train/validation split
Training Process:
- Binary classification: real vs. fake triples
- Loss: BCEWithLogitsLoss
- Optimizer: Adam with weight decay
- Metrics: Loss, Accuracy
Hyperparameters:
- Learning rate: 0.01
- Epochs: 50
- Embedding dim: 64
- Hidden dim: 128
- Dropout: 0.3
8. Model Comparison β
Comprehensive comparison of all 4 GNN architectures:
| Model | Parameters | Embedding Dim | Best For | Complexity |
|---|---|---|---|---|
| GCN | ~50K | 64 | Simple graphs | O(E Γ dΒ²) |
| GAT | ~75K | 64 | Varying importance | O(E Γ dΒ² Γ heads) |
| GraphSAGE | ~55K | 64 | Large graphs | O(S Γ dΒ²) |
| R-GCN | ~60K | 64 | Multi-relational | O(R Γ dΒ²) or O(B Γ dΒ²) |
Performance Metrics:
- Training loss curves
- Validation accuracy
- Convergence speed
- Memory usage
9. Embedding Visualization β
t-SNE Visualization:
- Reduce embeddings from 64D β 2D
- Color by entity type
- Compare all 4 models side-by-side
Visualization Grid:
βββββββββββββββ¬ββββββββββββββ
β GCN β GAT β
β Embeddings β Embeddings β
βββββββββββββββΌββββββββββββββ€
β GraphSAGE β R-GCN β
β Embeddings β Embeddings β
βββββββββββββββ΄ββββββββββββββ
Analysis:
- Cluster quality
- Separation of entity types
- Embedding space structure
10. Summary and Conclusions β
Key Takeaways:
- GCN: Best for simple, fast prototyping
- GAT: Best when interpretability matters
- GraphSAGE: Best for large-scale graphs
- R-GCN: Best for multi-relational KGs
Decision Matrix:
| Requirement | Recommended Model |
|---|---|
| Speed | GCN |
| Interpretability | GAT |
| Scale | GraphSAGE |
| Multi-relational | R-GCN |
| Temporal data | Temporal GNN |
| Inductive learning | GraphSAGE |
Next Steps:
- π§ Hyperparameter tuning
- π More advanced metrics (Hits@K, MRR)
- π Real-world datasets (FB15k-237, WN18RR)
- β° Temporal extensions
- π Integration with LLMs
π Theory Deep Dive
Message Passing Framework
All GNNs follow the message passing framework:
Message: Compute messages from neighbors
m_v = Ξ£_{uβN(v)} MSG(h_u, h_v, e_uv)Aggregate: Combine messages
m_v_agg = AGG({m_u : uβN(v)})Update: Update node representation
h_v_new = UPDATE(h_v, m_v_agg)
Over-smoothing Problem
Issue: Deep GNNs can make all node embeddings similar
Solutions:
- Skip connections (ResGNN)
- Layer normalization
- Dropout
- Limit number of layers (typically 2-3)
Relation-Aware Models
Challenge: Traditional GNNs treat all edges equally
R-GCN Solution:
- Separate weights per relation type
- Basis decomposition for efficiency
- Self-loops for self-information
π Running the Notebook
Prerequisites
pip install torch torch-geometric scikit-learn matplotlib seaborn tqdm numpy
Execution
cd /path/to/CA10_knowledge_graphs/notebooks
jupyter notebook 02_Graph_Neural_Networks.ipynb
Or execute all cells:
jupyter nbconvert --to notebook --execute 02_Graph_Neural_Networks.ipynb \\
--output 02_Graph_Neural_Networks_executed.ipynb
π Expected Outputs
Cell Outputs Include:
- β Device configuration (CPU/GPU)
- β Knowledge graph statistics
- β Model architectures
- β Parameter counts
- β Forward pass results
- β Attention weight analysis (GAT)
- β Training progress
- β Loss curves
- β Embedding visualizations
- β Performance comparison
Visualizations:
- π Training/validation loss curves
- π¨ t-SNE embedding plots
- π Attention weight distributions
- π Knowledge graph structure
- π Model comparison charts
π¬ Research Applications
1. Drug Discovery
- Task: Predict drug-disease interactions
- Model: R-GCN for multi-relational biomedical KG
- Relations: "treats", "causes", "interacts_with"
2. Recommendation Systems
- Task: Recommend products based on user behavior
- Model: GraphSAGE for large-scale graphs
- Nodes: Users, Products, Categories
3. Question Answering
- Task: Multi-hop reasoning over knowledge
- Model: R-GCN + Attention
- Example: "Who discovered the theory developed by Einstein?"
4. Link Prediction
- Task: Predict missing links in KG
- Model: All GNN models + scoring function
- Metrics: Hits@K, MRR, Mean Rank
π References
Key Papers:
- GCN: Kipf & Welling, "Semi-Supervised Classification with GCNs" (ICLR 2017)
- GAT: VeliΔkoviΔ et al., "Graph Attention Networks" (ICLR 2018)
- GraphSAGE: Hamilton et al., "Inductive Representation Learning" (NIPS 2017)
- R-GCN: Schlichtkrull et al., "Modeling Relational Data with GCNs" (ESWC 2018)
Additional Resources:
- PyTorch Geometric Documentation
- Stanford CS224W: Machine Learning with Graphs
- Distill.pub: "A Gentle Introduction to GNNs"
π Learning Outcomes
After completing this notebook, you will:
- β Understand GNN fundamentals
- β Implement 4 different GNN architectures
- β Apply GNNs to Knowledge Graphs
- β Compare model performance
- β Visualize learned embeddings
- β Choose appropriate models for tasks
π οΈ Troubleshooting
Common Issues:
1. Import Errors
pip install torch-scatter torch-sparse torch-geometric -f https://data.pyg.org/whl/torch-<version>.html
2. CUDA Out of Memory
- Reduce batch size
- Reduce embedding dimension
- Use CPU instead
3. Slow Training
- Use GPU if available
- Reduce number of layers
- Use GraphSAGE with sampling
π License
Part of the System2_in_AI course materials (CA10)
Happy Learning! π
For questions or issues, refer to the main CA10 README or project documentation.
Xet Storage Details
- Size:
- 10.2 kB
- Xet hash:
- bc989d24067c11f80189966f53d7919e7b17aa7986c906507675b968d47535d3
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.