{ "cells": [ { "cell_type": "markdown", "id": "f7d67608-8b00-430e-849b-7ac1ac1f7a08", "metadata": {}, "source": [ "--------------------------------------------\n", "**PHASE 1: EXPLAIN & BREAKDOWN (LEARNING PHASE)**\n", "--------------------------------------------\n", "\n", "## 1. Simple Explanation of Graph Neural Networks (GNNs)\n", "\n", "Graph Neural Networks (GNNs) are a specialized type of neural network designed to work with graph-structured data, where information is represented as nodes (entities) connected by edges (relationships). Unlike traditional neural networks that work with grid-like data (images) or sequences (text), GNNs can handle irregular, interconnected data structures like social networks, molecular structures, or knowledge graphs. The key innovation is that GNNs learn node representations by iteratively aggregating information from neighboring nodes, allowing them to capture both local and global patterns in the graph structure. This makes them perfect for tasks like predicting molecular properties, recommending friends on social media, or analyzing protein interactions.\n", "\n", "## 2. Detailed Roadmap with Concrete Examples\n", "\n", "**Step 1: Graph Fundamentals**\n", "- **Graph representation**: Adjacency matrix, edge list, node features\n", "- **Example**: Social network with users (nodes) and friendships (edges)\n", "\n", "**Step 2: Message Passing Framework**\n", "- **Aggregation**: How nodes collect information from neighbors\n", "- **Example**: In citation networks, a paper's importance depends on citing papers\n", "\n", "**Step 3: Basic GNN Architectures**\n", "- **Graph Convolutional Networks (GCNs)**: Smooth feature propagation\n", "- **Example**: Predicting research areas of papers based on citation patterns\n", "\n", "**Step 4: Advanced GNN Variants**\n", "- **GraphSAGE**: Sampling and aggregating from large graphs\n", "- **Example**: Recommending products by sampling user-item interactions\n", "\n", "**Step 5: Graph Attention Networks (GATs)**\n", "- **Attention mechanism**: Weighted neighbor importance\n", "- **Example**: Molecular property prediction where some atom bonds matter more\n", "\n", "**Step 6: Applications and Tasks**\n", "- **Node classification**: Predicting user categories in social networks\n", "- **Link prediction**: Suggesting new connections or relationships\n", "- **Graph classification**: Determining if a molecule is toxic or not\n", "\n", "## 3. Formula Memory AIDS Section\n", "\n", "**FORMULA: GCN Layer Update**\n", "$$H^{(l+1)} = \\sigma(\\tilde{A} H^{(l)} W^{(l)})$$\n", "\n", "**REAL-LIFE ANALOGY**: \"Gossip spreading in a neighborhood\"\n", "- $H^{(l)}$ = Current gossip each person knows (node features at layer l)\n", "- $\\tilde{A}$ = Normalized social network connections (how gossip spreads)\n", "- $W^{(l)}$ = Gossip filter (what parts of gossip are important)\n", "- $\\sigma$ = Excitement function (how people react to gossip)\n", "- $H^{(l+1)}$ = Updated gossip after one round of spreading\n", "\n", "**MEMORY TRICK**: \"GCN = Gossip Convolutional Network!\"\n", "\n", "**FORMULA: Message Passing**\n", "$$m_{ij}^{(l)} = \\text{Message}(h_i^{(l)}, h_j^{(l)}, e_{ij})$$\n", "$$h_i^{(l+1)} = \\text{Update}(h_i^{(l)}, \\text{Aggregate}(\\{m_{ij}^{(l)} : j \\in N(i)\\}))$$\n", "\n", "**REAL-LIFE ANALOGY**: \"Group chat dynamics\"\n", "- $m_{ij}^{(l)}$ = Message from person i to person j (edge features)\n", "- $h_i^{(l)}$ = Person i's current knowledge/state\n", "- $N(i)$ = Person i's friend group\n", "- **Aggregate** = Reading all messages in group chat\n", "- **Update** = Updating your opinion based on friends' messages\n", "\n", "**MEMORY TRICK**: \"Messages, Aggregate, Update - like checking WhatsApp!\"\n", "\n", "**FORMULA: Graph Attention**\n", "$$\\alpha_{ij} = \\frac{\\exp(\\text{LeakyReLU}(a^T[W h_i \\| W h_j]))}{\\sum_{k \\in N(i)} \\exp(\\text{LeakyReLU}(a^T[W h_i \\| W h_k]))}$$\n", "\n", "**REAL-LIFE ANALOGY**: \"Choosing who to listen to in a conversation\"\n", "- $\\alpha_{ij}$ = How much attention you pay to person j\n", "- $W h_i, W h_j$ = Processed versions of what you and person j are saying\n", "- $a^T$ = Your personal preference for conversation topics\n", "- **Softmax** = You can only pay 100% attention total, so you distribute it\n", "\n", "**MEMORY TRICK**: \"Attention = Who gets your EAR in a crowd!\"\n", "\n", "## 4. Step-by-Step Numerical Example\n", "\n", "**Example: 3-node friendship network predicting user interests**\n", "\n", "**Graph Setup:**\n", "- Node 0: Alice (features: [0.8, 0.2] - likes tech, dislikes sports)\n", "- Node 1: Bob (features: [0.3, 0.9] - neutral on tech, loves sports) \n", "- Node 2: Carol (features: [0.6, 0.4] - likes both moderately)\n", "- Edges: Alice-Bob, Bob-Carol (friendship connections)\n", "\n", "**Adjacency Matrix A:**\n", "```\n", " A B C\n", "A [[0, 1, 0],\n", "B [1, 0, 1],\n", "C [0, 1, 0]]\n", "```\n", "\n", "**Normalized Adjacency Matrix à (adding self-loops and normalization):**\n", "```\n", "à = [[0.5, 0.5, 0.0],\n", " [0.33, 0.33, 0.33],\n", " [0.0, 0.5, 0.5]]\n", "```\n", "\n", "**Initial Features H⁰:**\n", "```\n", "H⁰ = [[0.8, 0.2], # Alice\n", " [0.3, 0.9], # Bob\n", " [0.6, 0.4]] # Carol\n", "```\n", "\n", "**Weight Matrix W⁰ (2x2 for simplicity):**\n", "```\n", "W⁰ = [[0.5, 0.8],\n", " [0.3, 0.7]]\n", "```\n", "\n", "**Forward Pass Calculation:**\n", "```\n", "H¹ = σ(Ã × H⁰ × W⁰)\n", "\n", "Step 1: Ã × H⁰ (neighbor aggregation)\n", "[[0.5, 0.5, 0.0], [[0.8, 0.2], [[0.55, 0.55],\n", " [0.33, 0.33, 0.33] × [0.3, 0.9], = [0.57, 0.5],\n", " [0.0, 0.5, 0.5]] [0.6, 0.4]] [0.45, 0.65]]\n", "\n", "Step 2: × W⁰ (feature transformation)\n", "[[0.55, 0.55], [[0.5, 0.8], [[0.44, 0.83],\n", " [0.57, 0.5], × [0.3, 0.7]] = [0.435, 0.806],\n", " [0.45, 0.65]] [0.42, 0.815]]\n", "\n", "Step 3: σ (ReLU activation)\n", "H¹ = [[0.44, 0.83], # Alice's updated features\n", " [0.435, 0.806], # Bob's updated features \n", " [0.42, 0.815]] # Carol's updated features\n", "```\n", "\n", "**Interpretation:** After one GNN layer, Alice's features moved closer to Bob's (her only neighbor), showing how social influence affects interests!\n", "\n", "## 5. Real-World AI Use Case\n", "\n", "**Drug Discovery - Molecular Property Prediction:**\n", "GNNs are revolutionizing pharmaceutical research by predicting molecular properties like toxicity, solubility, and bioactivity. In this application:\n", "- **Nodes**: Atoms (carbon, oxygen, nitrogen, etc.)\n", "- **Edges**: Chemical bonds (single, double, triple bonds)\n", "- **Node Features**: Atom type, charge, hybridization\n", "- **Edge Features**: Bond type, bond length, aromaticity\n", "\n", "The GNN learns to predict whether a molecule will be toxic, effective against specific diseases, or have good absorption properties. This dramatically reduces the need for expensive laboratory testing and accelerates drug discovery from years to months.\n", "\n", "**Impact**: Companies like DeepMind (AlphaFold) and pharmaceutical giants are using GNNs to discover new antibiotics and cancer drugs, potentially saving millions of lives.\n", "\n", "## 6. Tips for Mastering GNNs\n", "\n", "**Practice Sources:**\n", "- **PyTorch Geometric (PyG)**: Start with their tutorials on node classification\n", "- **DGL (Deep Graph Library)**: Practice on their built-in datasets\n", "- **Spektral**: TensorFlow-based graph neural networks\n", "\n", "**Key Datasets to Practice:**\n", "- **Cora/CiteSeer**: Citation networks for node classification\n", "- **MUTAG**: Molecular graphs for graph classification \n", "- **Reddit**: Large-scale social network for scalability practice\n", "\n", "**Problem-Solving Strategy:**\n", "1. **Start small**: 3-5 nodes manually to understand message passing\n", "2. **Visualize**: Use NetworkX to plot your graphs\n", "3. **Debug shapes**: GNNs have tricky tensor dimensions\n", "4. **Experiment**: Try different aggregation functions (mean, max, sum)\n", "5. **Scale gradually**: Small graphs → medium → large with sampling\n", "\n", "**Common Pitfalls to Avoid:**\n", "- **Over-smoothing**: Too many layers make all nodes similar\n", "- **Under-reaching**: Too few layers miss global patterns\n", "- **Dimension mismatches**: Carefully track node/edge feature sizes\n", "- **Sparse matrix handling**: Learn efficient sparse operations" ] }, { "cell_type": "code", "execution_count": 5, "id": "59edcfb0-b6e8-4645-8cf3-a6492b5bebfd", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "2025-07-18 11:54:14,017 - INFO - Starting GNN training pipeline...\n", "2025-07-18 11:54:14,017 - INFO - Using device: cpu\n", "2025-07-18 11:54:14,018 - INFO - Using Apple Silicon MPS acceleration\n", "2025-07-18 11:54:14,018 - INFO - Loading Cora dataset...\n", "2025-07-18 11:54:14,023 - INFO - Dataset: Cora()\n", "2025-07-18 11:54:14,024 - INFO - Number of graphs: 1\n", "2025-07-18 11:54:14,025 - INFO - Number of features: 1433\n", "2025-07-18 11:54:14,026 - INFO - Number of classes: 7\n", "2025-07-18 11:54:14,026 - INFO - Number of nodes: 2708\n", "2025-07-18 11:54:14,026 - INFO - Number of edges: 10556\n", "2025-07-18 11:54:14,026 - INFO - Average node degree: 3.90\n", "2025-07-18 11:54:14,027 - INFO - Training nodes: 140\n", "2025-07-18 11:54:14,027 - INFO - Validation nodes: 500\n", "2025-07-18 11:54:14,027 - INFO - Test nodes: 1000\n", "2025-07-18 11:54:14,028 - INFO - Data split ratios - Train: 0.052, Val: 0.185, Test: 0.369\n", "2025-07-18 11:54:14,048 - INFO - Creating graph visualization...\n", "2025-07-18 11:54:20,240 - INFO - Graph visualization saved to graph_visualization.png\n", "2025-07-18 11:54:20,240 - INFO - Training configuration: {'hidden_dim': 32, 'num_layers': 2, 'dropout': 0.5, 'learning_rate': 0.001, 'weight_decay': 0.0005, 'epochs': 200, 'patience': 20, 'attention_heads': 8}\n", "2025-07-18 11:54:20,241 - INFO - \n", "==================================================\n", "2025-07-18 11:54:20,241 - INFO - Training GCN\n", "2025-07-18 11:54:20,241 - INFO - ==================================================\n", "2025-07-18 11:54:20,242 - INFO - Training GCN model...\n", "2025-07-18 11:54:20,441 - INFO - GCN Model initialized with 1433 input features, 32 hidden dim, 7 classes\n", "2025-07-18 11:54:20,442 - INFO - Model parameters: 46,119\n", "2025-07-18 11:54:21,583 - INFO - Epoch 20/200 - Train Loss: 1.9194, Train Acc: 0.7857, Val Loss: 1.9314, Val Acc: 0.6880\n", "2025-07-18 11:54:21,830 - INFO - Epoch 40/200 - Train Loss: 1.8824, Train Acc: 0.8714, Val Loss: 1.9118, Val Acc: 0.7580\n", "2025-07-18 11:54:22,072 - INFO - Epoch 60/200 - Train Loss: 1.8367, Train Acc: 0.9214, Val Loss: 1.8873, Val Acc: 0.7680\n", "2025-07-18 11:54:22,313 - INFO - Epoch 80/200 - Train Loss: 1.7875, Train Acc: 0.8857, Val Loss: 1.8592, Val Acc: 0.7740\n", "2025-07-18 11:54:22,431 - INFO - Early stopping at epoch 90\n", "2025-07-18 11:54:22,443 - INFO - GCN Final Test Accuracy: 0.7930\n", "2025-07-18 11:54:22,445 - INFO - GCN training completed and saved\n", "2025-07-18 11:54:22,445 - INFO - \n", "==================================================\n", "2025-07-18 11:54:22,445 - INFO - Training GraphSAGE\n", "2025-07-18 11:54:22,445 - INFO - ==================================================\n", "2025-07-18 11:54:22,446 - INFO - Training GraphSAGE model...\n", "2025-07-18 11:54:22,459 - INFO - GraphSAGE Model initialized with 1433 input features, 32 hidden dim, 7 classes\n", "2025-07-18 11:54:22,461 - INFO - Model parameters: 92,199\n", "2025-07-18 11:54:22,972 - INFO - Epoch 20/200 - Train Loss: 1.9226, Train Acc: 0.2929, Val Loss: 1.9494, Val Acc: 0.2020\n", "2025-07-18 11:54:23,306 - INFO - Epoch 40/200 - Train Loss: 1.8653, Train Acc: 0.4214, Val Loss: 1.9226, Val Acc: 0.2440\n", "2025-07-18 11:54:23,640 - INFO - Epoch 60/200 - Train Loss: 1.7637, Train Acc: 0.8000, Val Loss: 1.8790, Val Acc: 0.4360\n", "2025-07-18 11:54:23,976 - INFO - Epoch 80/200 - Train Loss: 1.6420, Train Acc: 0.8857, Val Loss: 1.8200, Val Acc: 0.6080\n", "2025-07-18 11:54:24,300 - INFO - Epoch 100/200 - Train Loss: 1.4988, Train Acc: 0.9500, Val Loss: 1.7470, Val Acc: 0.6640\n", "2025-07-18 11:54:24,630 - INFO - Epoch 120/200 - Train Loss: 1.3248, Train Acc: 0.9571, Val Loss: 1.6629, Val Acc: 0.7080\n", "2025-07-18 11:54:24,989 - INFO - Epoch 140/200 - Train Loss: 1.1383, Train Acc: 0.9714, Val Loss: 1.5735, Val Acc: 0.7480\n", "2025-07-18 11:54:25,308 - INFO - Epoch 160/200 - Train Loss: 1.0036, Train Acc: 0.9786, Val Loss: 1.4778, Val Acc: 0.7640\n", "2025-07-18 11:54:25,632 - INFO - Epoch 180/200 - Train Loss: 0.8511, Train Acc: 0.9714, Val Loss: 1.3865, Val Acc: 0.7800\n", "2025-07-18 11:54:25,739 - INFO - Early stopping at epoch 187\n", "2025-07-18 11:54:25,749 - INFO - GraphSAGE Final Test Accuracy: 0.7680\n", "2025-07-18 11:54:25,751 - INFO - GraphSAGE training completed and saved\n", "2025-07-18 11:54:25,752 - INFO - \n", "==================================================\n", "2025-07-18 11:54:25,752 - INFO - Training GAT\n", "2025-07-18 11:54:25,753 - INFO - ==================================================\n", "2025-07-18 11:54:25,753 - INFO - Training GAT model...\n", "2025-07-18 11:54:25,776 - INFO - GAT Model initialized with 1433 input features, 32 hidden dim, 7 classes, 8 attention heads\n", "2025-07-18 11:54:25,778 - INFO - Model parameters: 369,429\n", "2025-07-18 11:54:28,023 - INFO - Epoch 20/200 - Train Loss: 1.8903, Train Acc: 0.7857, Val Loss: 1.9061, Val Acc: 0.7900\n", "2025-07-18 11:54:28,464 - INFO - Epoch 40/200 - Train Loss: 1.7788, Train Acc: 0.9143, Val Loss: 1.8423, Val Acc: 0.7960\n", "2025-07-18 11:54:28,605 - INFO - Early stopping at epoch 46\n", "2025-07-18 11:54:28,618 - INFO - GAT Final Test Accuracy: 0.8190\n", "2025-07-18 11:54:28,622 - INFO - GAT training completed and saved\n", "2025-07-18 11:54:28,622 - INFO - Creating training curves...\n", "2025-07-18 11:54:29,106 - INFO - Training curves saved to training_curves.png\n", "2025-07-18 11:54:29,106 - INFO - Creating embeddings visualization...\n", "2025-07-18 11:54:36,376 - INFO - Embeddings visualization saved to embeddings_tsne.png\n", "2025-07-18 11:54:36,377 - INFO - Saving results summary...\n", "2025-07-18 11:54:36,377 - INFO - Results summary saved to results_summary.json\n", "2025-07-18 11:54:36,378 - INFO - \n", "============================================================\n", "2025-07-18 11:54:36,378 - INFO - FINAL RESULTS COMPARISON\n", "2025-07-18 11:54:36,378 - INFO - ============================================================\n", "2025-07-18 11:54:36,378 - INFO - GCN - Test Accuracy: 0.7930\n", "2025-07-18 11:54:36,378 - INFO - GraphSAGE - Test Accuracy: 0.7680\n", "2025-07-18 11:54:36,379 - INFO - GAT - Test Accuracy: 0.8190\n", "2025-07-18 11:54:36,379 - INFO - \n", "Best performing model: GAT with accuracy: 0.8190\n", "2025-07-18 11:54:36,379 - INFO - \n", "All training artifacts saved:\n", "2025-07-18 11:54:36,379 - INFO - - Model checkpoints: best_*_model.pth\n", "2025-07-18 11:54:36,379 - INFO - - Full models: *_full_model.pkl\n", "2025-07-18 11:54:36,380 - INFO - - Training curves: training_curves.png\n", "2025-07-18 11:54:36,380 - INFO - - Embeddings visualization: embeddings_tsne.png\n", "2025-07-18 11:54:36,380 - INFO - - Graph visualization: graph_visualization.png\n", "2025-07-18 11:54:36,380 - INFO - - Results summary: results_summary.json\n", "2025-07-18 11:54:36,380 - INFO - - Training logs: gnn_training.log\n", "2025-07-18 11:54:36,381 - INFO - \n", "GNN training pipeline completed successfully!\n" ] } ], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import torch.optim as optim\n", "from torch_geometric.datasets import Planetoid\n", "from torch_geometric.nn import GCNConv, SAGEConv, GATConv, global_mean_pool\n", "from torch_geometric.data import DataLoader\n", "from torch_geometric.transforms import NormalizeFeatures\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import pandas as pd\n", "import numpy as np\n", "import networkx as nx\n", "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n", "from sklearn.manifold import TSNE\n", "import json\n", "import pickle\n", "import logging\n", "import os\n", "from datetime import datetime\n", "import warnings\n", "warnings.filterwarnings('ignore')\n", "\n", "logging.basicConfig(\n", " level=logging.INFO,\n", " format='%(asctime)s - %(levelname)s - %(message)s',\n", " handlers=[\n", " logging.FileHandler('gnn_training.log'),\n", " logging.StreamHandler()\n", " ]\n", ")\n", "logger = logging.getLogger(__name__)\n", "\n", "class GCNModel(nn.Module):\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5):\n", " super(GCNModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " self.convs = nn.ModuleList()\n", " self.convs.append(GCNConv(num_features, hidden_dim))\n", " \n", " for _ in range(num_layers - 2):\n", " self.convs.append(GCNConv(hidden_dim, hidden_dim))\n", " \n", " self.convs.append(GCNConv(hidden_dim, num_classes))\n", " \n", " logger.info(f\"GCN Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index)\n", " x = F.relu(x)\n", " x = F.dropout(x, p=self.dropout, training=self.training)\n", " \n", " x = self.convs[-1](x, edge_index)\n", " return F.log_softmax(x, dim=1)\n", "\n", "class GraphSAGEModel(nn.Module):\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5):\n", " super(GraphSAGEModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " self.convs = nn.ModuleList()\n", " self.convs.append(SAGEConv(num_features, hidden_dim))\n", " \n", " for _ in range(num_layers - 2):\n", " self.convs.append(SAGEConv(hidden_dim, hidden_dim))\n", " \n", " self.convs.append(SAGEConv(hidden_dim, num_classes))\n", " \n", " logger.info(f\"GraphSAGE Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index)\n", " x = F.relu(x)\n", " x = F.dropout(x, p=self.dropout, training=self.training)\n", " \n", " x = self.convs[-1](x, edge_index)\n", " return F.log_softmax(x, dim=1)\n", "\n", "class GATModel(nn.Module):\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5, heads=8):\n", " super(GATModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " self.convs = nn.ModuleList()\n", " self.convs.append(GATConv(num_features, hidden_dim, heads=heads, dropout=dropout))\n", " \n", " for _ in range(num_layers - 2):\n", " self.convs.append(GATConv(hidden_dim * heads, hidden_dim, heads=heads, dropout=dropout))\n", " \n", " self.convs.append(GATConv(hidden_dim * heads, num_classes, heads=1, dropout=dropout))\n", " \n", " logger.info(f\"GAT Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes, {heads} attention heads\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index)\n", " x = F.relu(x)\n", " x = F.dropout(x, p=self.dropout, training=self.training)\n", " \n", " x = self.convs[-1](x, edge_index)\n", " return F.log_softmax(x, dim=1)\n", "\n", "def load_and_explore_data():\n", " logger.info(\"Loading Cora dataset...\")\n", " dataset = Planetoid(root='/tmp/Cora', name='Cora', transform=NormalizeFeatures())\n", " data = dataset[0]\n", " \n", " logger.info(f\"Dataset: {dataset}\")\n", " logger.info(f\"Number of graphs: {len(dataset)}\")\n", " logger.info(f\"Number of features: {dataset.num_features}\")\n", " logger.info(f\"Number of classes: {dataset.num_classes}\")\n", " logger.info(f\"Number of nodes: {data.num_nodes}\")\n", " logger.info(f\"Number of edges: {data.num_edges}\")\n", " logger.info(f\"Average node degree: {data.num_edges / data.num_nodes:.2f}\")\n", " logger.info(f\"Training nodes: {data.train_mask.sum()}\")\n", " logger.info(f\"Validation nodes: {data.val_mask.sum()}\")\n", " logger.info(f\"Test nodes: {data.test_mask.sum()}\")\n", " \n", " train_ratio = data.train_mask.sum() / data.num_nodes\n", " val_ratio = data.val_mask.sum() / data.num_nodes\n", " test_ratio = data.test_mask.sum() / data.num_nodes\n", " logger.info(f\"Data split ratios - Train: {train_ratio:.3f}, Val: {val_ratio:.3f}, Test: {test_ratio:.3f}\")\n", " \n", " return dataset, data\n", "\n", "def create_graph_visualization(data, save_path='graph_visualization.png'):\n", " logger.info(\"Creating graph visualization...\")\n", " \n", " edge_index = data.edge_index.cpu().numpy()\n", " node_labels = data.y.cpu().numpy()\n", " \n", " G = nx.Graph()\n", " G.add_edges_from(edge_index.T)\n", " \n", " fig, ax = plt.subplots(figsize=(12, 8))\n", " pos = nx.spring_layout(G, k=0.5, iterations=50)\n", " \n", " nx.draw(G, pos, node_color=node_labels, node_size=20, \n", " with_labels=False, cmap='Set3', alpha=0.7, ax=ax)\n", " \n", " ax.set_title(\"Cora Citation Network Visualization\")\n", " \n", " sm = plt.cm.ScalarMappable(cmap='Set3', norm=plt.Normalize(vmin=node_labels.min(), vmax=node_labels.max()))\n", " sm.set_array([])\n", " plt.colorbar(sm, ax=ax, label='Node Classes')\n", " \n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " logger.info(f\"Graph visualization saved to {save_path}\")\n", "\n", "def train_model(model, data, optimizer, criterion, device):\n", " model.train()\n", " optimizer.zero_grad()\n", " \n", " out = model(data.x, data.edge_index)\n", " loss = criterion(out[data.train_mask], data.y[data.train_mask])\n", " loss.backward()\n", " optimizer.step()\n", " \n", " with torch.no_grad():\n", " pred = out[data.train_mask].argmax(dim=1)\n", " train_acc = accuracy_score(data.y[data.train_mask].cpu(), pred.cpu())\n", " \n", " return loss.item(), train_acc\n", "\n", "def validate_model(model, data, criterion, device):\n", " model.eval()\n", " with torch.no_grad():\n", " out = model(data.x, data.edge_index)\n", " val_loss = criterion(out[data.val_mask], data.y[data.val_mask])\n", " pred = out[data.val_mask].argmax(dim=1)\n", " val_acc = accuracy_score(data.y[data.val_mask].cpu(), pred.cpu())\n", " \n", " return val_loss.item(), val_acc\n", "\n", "def test_model(model, data, device):\n", " model.eval()\n", " with torch.no_grad():\n", " out = model(data.x, data.edge_index)\n", " pred = out[data.test_mask].argmax(dim=1)\n", " test_acc = accuracy_score(data.y[data.test_mask].cpu(), pred.cpu())\n", " \n", " y_true = data.y[data.test_mask].cpu().numpy()\n", " y_pred = pred.cpu().numpy()\n", " \n", " report = classification_report(y_true, y_pred, output_dict=True)\n", " conf_matrix = confusion_matrix(y_true, y_pred)\n", " \n", " return test_acc, report, conf_matrix, out\n", "\n", "def train_and_evaluate_model(model_class, model_name, data, device, config):\n", " logger.info(f\"Training {model_name} model...\")\n", " \n", " if model_name == 'GAT':\n", " model = model_class(\n", " num_features=data.num_features,\n", " hidden_dim=config['hidden_dim'],\n", " num_classes=data.y.max().item() + 1,\n", " num_layers=config['num_layers'],\n", " dropout=config['dropout'],\n", " heads=config['attention_heads']\n", " ).to(device)\n", " else:\n", " model = model_class(\n", " num_features=data.num_features,\n", " hidden_dim=config['hidden_dim'],\n", " num_classes=data.y.max().item() + 1,\n", " num_layers=config['num_layers'],\n", " dropout=config['dropout']\n", " ).to(device)\n", " \n", " optimizer = optim.Adam(model.parameters(), lr=config['learning_rate'], weight_decay=config['weight_decay'])\n", " criterion = nn.NLLLoss()\n", " \n", " logger.info(f\"Model parameters: {sum(p.numel() for p in model.parameters()):,}\")\n", " \n", " train_losses, train_accs = [], []\n", " val_losses, val_accs = [], []\n", " best_val_acc = 0\n", " patience_counter = 0\n", " \n", " for epoch in range(config['epochs']):\n", " train_loss, train_acc = train_model(model, data, optimizer, criterion, device)\n", " val_loss, val_acc = validate_model(model, data, criterion, device)\n", " \n", " train_losses.append(train_loss)\n", " train_accs.append(train_acc)\n", " val_losses.append(val_loss)\n", " val_accs.append(val_acc)\n", " \n", " if val_acc > best_val_acc:\n", " best_val_acc = val_acc\n", " patience_counter = 0\n", " torch.save(model.state_dict(), f'best_{model_name.lower()}_model.pth')\n", " else:\n", " patience_counter += 1\n", " \n", " if (epoch + 1) % 20 == 0:\n", " logger.info(f\"Epoch {epoch+1}/{config['epochs']} - \"\n", " f\"Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, \"\n", " f\"Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}\")\n", " \n", " if patience_counter >= config['patience']:\n", " logger.info(f\"Early stopping at epoch {epoch+1}\")\n", " break\n", " \n", " model.load_state_dict(torch.load(f'best_{model_name.lower()}_model.pth'))\n", " test_acc, report, conf_matrix, embeddings = test_model(model, data, device)\n", " \n", " logger.info(f\"{model_name} Final Test Accuracy: {test_acc:.4f}\")\n", " \n", " return {\n", " 'model': model,\n", " 'train_losses': train_losses,\n", " 'train_accs': train_accs,\n", " 'val_losses': val_losses,\n", " 'val_accs': val_accs,\n", " 'test_acc': test_acc,\n", " 'classification_report': report,\n", " 'confusion_matrix': conf_matrix,\n", " 'embeddings': embeddings\n", " }\n", "\n", "def create_training_plots(results, save_path='training_curves.png'):\n", " logger.info(\"Creating training curves...\")\n", " \n", " fig, axes = plt.subplots(2, 3, figsize=(18, 12))\n", " \n", " model_names = list(results.keys())\n", " colors = ['blue', 'red', 'green']\n", " \n", " for i, (model_name, color) in enumerate(zip(model_names, colors)):\n", " result = results[model_name]\n", " \n", " axes[0, i].plot(result['train_losses'], color=color, label='Train Loss')\n", " axes[0, i].plot(result['val_losses'], color=color, linestyle='--', label='Val Loss')\n", " axes[0, i].set_title(f'{model_name} - Loss Curves')\n", " axes[0, i].set_xlabel('Epoch')\n", " axes[0, i].set_ylabel('Loss')\n", " axes[0, i].legend()\n", " axes[0, i].grid(True)\n", " \n", " axes[1, i].plot(result['train_accs'], color=color, label='Train Acc')\n", " axes[1, i].plot(result['val_accs'], color=color, linestyle='--', label='Val Acc')\n", " axes[1, i].set_title(f'{model_name} - Accuracy Curves')\n", " axes[1, i].set_xlabel('Epoch')\n", " axes[1, i].set_ylabel('Accuracy')\n", " axes[1, i].legend()\n", " axes[1, i].grid(True)\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " logger.info(f\"Training curves saved to {save_path}\")\n", "\n", "def create_embeddings_visualization(results, data, save_path='embeddings_tsne.png'):\n", " logger.info(\"Creating embeddings visualization...\")\n", " \n", " fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", " \n", " model_names = list(results.keys())\n", " \n", " for i, model_name in enumerate(model_names):\n", " embeddings = results[model_name]['embeddings'].cpu().numpy()\n", " labels = data.y.cpu().numpy()\n", " \n", " tsne = TSNE(n_components=2, random_state=42, perplexity=30)\n", " embeddings_2d = tsne.fit_transform(embeddings)\n", " \n", " scatter = axes[i].scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], \n", " c=labels, cmap='Set3', alpha=0.7, s=20)\n", " axes[i].set_title(f'{model_name} - Node Embeddings (t-SNE)')\n", " axes[i].set_xlabel('t-SNE 1')\n", " axes[i].set_ylabel('t-SNE 2')\n", " plt.colorbar(scatter, ax=axes[i])\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " logger.info(f\"Embeddings visualization saved to {save_path}\")\n", "\n", "def save_results_summary(results, config, save_path='results_summary.json'):\n", " logger.info(\"Saving results summary...\")\n", " \n", " summary = {\n", " 'experiment_config': config,\n", " 'model_performance': {},\n", " 'timestamp': datetime.now().isoformat()\n", " }\n", " \n", " for model_name, result in results.items():\n", " summary['model_performance'][model_name] = {\n", " 'test_accuracy': float(result['test_acc']),\n", " 'final_train_accuracy': float(result['train_accs'][-1]),\n", " 'final_val_accuracy': float(result['val_accs'][-1]),\n", " 'best_val_accuracy': float(max(result['val_accs'])),\n", " 'precision_macro': float(result['classification_report']['macro avg']['precision']),\n", " 'recall_macro': float(result['classification_report']['macro avg']['recall']),\n", " 'f1_macro': float(result['classification_report']['macro avg']['f1-score'])\n", " }\n", " \n", " with open(save_path, 'w') as f:\n", " json.dump(summary, f, indent=2)\n", " \n", " logger.info(f\"Results summary saved to {save_path}\")\n", "\n", "def main():\n", " logger.info(\"Starting GNN training pipeline...\")\n", " \n", " device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", " logger.info(f\"Using device: {device}\")\n", " \n", " if torch.backends.mps.is_available():\n", " device = torch.device('mps')\n", " logger.info(\"Using Apple Silicon MPS acceleration\")\n", " \n", " dataset, data = load_and_explore_data()\n", " data = data.to(device)\n", " \n", " create_graph_visualization(data)\n", " \n", " config = {\n", " 'hidden_dim': 32,\n", " 'num_layers': 2,\n", " 'dropout': 0.5,\n", " 'learning_rate': 0.001,\n", " 'weight_decay': 5e-4,\n", " 'epochs': 200,\n", " 'patience': 20,\n", " 'attention_heads': 8\n", " }\n", " \n", " logger.info(f\"Training configuration: {config}\")\n", " \n", " models = {\n", " 'GCN': GCNModel,\n", " 'GraphSAGE': GraphSAGEModel,\n", " 'GAT': GATModel\n", " }\n", " \n", " results = {}\n", " \n", " for model_name, model_class in models.items():\n", " logger.info(f\"\\n{'='*50}\")\n", " logger.info(f\"Training {model_name}\")\n", " logger.info(f\"{'='*50}\")\n", " \n", " result = train_and_evaluate_model(model_class, model_name, data, device, config)\n", " results[model_name] = result\n", " \n", " with open(f'{model_name.lower()}_full_model.pkl', 'wb') as f:\n", " pickle.dump(result['model'], f)\n", " \n", " logger.info(f\"{model_name} training completed and saved\")\n", " \n", " create_training_plots(results)\n", " create_embeddings_visualization(results, data)\n", " save_results_summary(results, config)\n", " \n", " logger.info(\"\\n\" + \"=\"*60)\n", " logger.info(\"FINAL RESULTS COMPARISON\")\n", " logger.info(\"=\"*60)\n", " \n", " for model_name, result in results.items():\n", " logger.info(f\"{model_name:12} - Test Accuracy: {result['test_acc']:.4f}\")\n", " \n", " best_model = max(results.items(), key=lambda x: x[1]['test_acc'])\n", " logger.info(f\"\\nBest performing model: {best_model[0]} with accuracy: {best_model[1]['test_acc']:.4f}\")\n", " \n", " logger.info(\"\\nAll training artifacts saved:\")\n", " logger.info(\"- Model checkpoints: best_*_model.pth\")\n", " logger.info(\"- Full models: *_full_model.pkl\")\n", " logger.info(\"- Training curves: training_curves.png\")\n", " logger.info(\"- Embeddings visualization: embeddings_tsne.png\")\n", " logger.info(\"- Graph visualization: graph_visualization.png\")\n", " logger.info(\"- Results summary: results_summary.json\")\n", " logger.info(\"- Training logs: gnn_training.log\")\n", " \n", " logger.info(\"\\nGNN training pipeline completed successfully!\")\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "code", "execution_count": null, "id": "7efc8f6a-9293-42be-b891-e3feaa6471c3", "metadata": {}, "outputs": [], "source": [ "# Import all necessary libraries for graph neural networks, visualization, and logging\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import torch.optim as optim\n", "from torch_geometric.datasets import Planetoid # PyTorch Geometric dataset loader\n", "from torch_geometric.nn import GCNConv, SAGEConv, GATConv, global_mean_pool # GNN layer types\n", "from torch_geometric.data import DataLoader\n", "from torch_geometric.transforms import NormalizeFeatures # Data preprocessing\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import pandas as pd\n", "import numpy as np\n", "import networkx as nx # For graph visualization\n", "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n", "from sklearn.manifold import TSNE # For dimensionality reduction visualization\n", "import json\n", "import pickle\n", "import logging\n", "import os\n", "from datetime import datetime\n", "import warnings\n", "warnings.filterwarnings('ignore') # Suppress non-critical warnings\n", "\n", "# Configure comprehensive logging to both file and console\n", "# This replaces traditional comments with runtime information\n", "logging.basicConfig(\n", " level=logging.INFO,\n", " format='%(asctime)s - %(levelname)s - %(message)s',\n", " handlers=[\n", " logging.FileHandler('gnn_training.log'), # Save logs to file\n", " logging.StreamHandler() # Display logs in console\n", " ]\n", ")\n", "logger = logging.getLogger(__name__)\n", "\n", "class GCNModel(nn.Module):\n", " \"\"\"\n", " Graph Convolutional Network (GCN) implementation\n", " \n", " GCN Architecture Rationale:\n", " - Uses spectral approach to graph convolutions\n", " - Simple and effective for node classification\n", " - Good baseline model for graph learning tasks\n", " \n", " Parameters chosen for stability:\n", " - hidden_dim=32: Small enough to prevent overfitting on limited training data (140 nodes)\n", " - num_layers=2: Avoids over-smoothing while capturing local graph structure\n", " - dropout=0.5: Regularization to prevent overfitting on small training set\n", " \"\"\"\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5):\n", " super(GCNModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " # Create a list of GCN layers - ModuleList ensures proper parameter registration\n", " self.convs = nn.ModuleList()\n", " \n", " # First layer: input features -> hidden dimension\n", " self.convs.append(GCNConv(num_features, hidden_dim))\n", " \n", " # Hidden layers: hidden -> hidden (if num_layers > 2)\n", " for _ in range(num_layers - 2):\n", " self.convs.append(GCNConv(hidden_dim, hidden_dim))\n", " \n", " # Final layer: hidden -> number of classes (no activation, will use log_softmax)\n", " self.convs.append(GCNConv(hidden_dim, num_classes))\n", " \n", " logger.info(f\"GCN Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " \"\"\"\n", " Forward pass through GCN layers\n", " \n", " Args:\n", " x: Node feature matrix [num_nodes, num_features]\n", " edge_index: Graph connectivity [2, num_edges] \n", " batch: Batch assignment (unused for single graph)\n", " \n", " Returns:\n", " Log probabilities for each node [num_nodes, num_classes]\n", " \"\"\"\n", " # Process through all layers except the last one\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index) # Graph convolution\n", " x = F.relu(x) # Non-linear activation\n", " x = F.dropout(x, p=self.dropout, training=self.training) # Regularization\n", " \n", " # Final layer without activation (will apply log_softmax)\n", " x = self.convs[-1](x, edge_index)\n", " \n", " # Return log probabilities for stable numerical computation\n", " return F.log_softmax(x, dim=1)\n", "\n", "class GraphSAGEModel(nn.Module):\n", " \"\"\"\n", " GraphSAGE (Sample and Aggregate) implementation\n", " \n", " GraphSAGE Architecture Rationale:\n", " - Uses sampling and aggregation instead of spectral methods\n", " - More scalable to large graphs than GCN\n", " - Better at handling heterogeneous neighborhoods\n", " \n", " Key differences from GCN:\n", " - Samples fixed-size neighborhoods for scalability\n", " - Uses mean aggregation by default\n", " - More parameters due to separate aggregation and update functions\n", " \"\"\"\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5):\n", " super(GraphSAGEModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " # SAGEConv layers - each layer samples and aggregates from neighbors\n", " self.convs = nn.ModuleList()\n", " self.convs.append(SAGEConv(num_features, hidden_dim))\n", " \n", " # Hidden layers maintain consistent dimensionality\n", " for _ in range(num_layers - 2):\n", " self.convs.append(SAGEConv(hidden_dim, hidden_dim))\n", " \n", " # Output layer projects to class space\n", " self.convs.append(SAGEConv(hidden_dim, num_classes))\n", " \n", " logger.info(f\"GraphSAGE Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " \"\"\"\n", " Forward pass through GraphSAGE layers\n", " \n", " GraphSAGE Process:\n", " 1. Sample neighbors for each node\n", " 2. Aggregate neighbor features (mean by default)\n", " 3. Concatenate with node's own features\n", " 4. Apply linear transformation\n", " \"\"\"\n", " # Apply GraphSAGE convolutions with ReLU and dropout\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index) # Sample and aggregate\n", " x = F.relu(x) # Non-linearity\n", " x = F.dropout(x, p=self.dropout, training=self.training) # Regularization\n", " \n", " # Final layer without activation\n", " x = self.convs[-1](x, edge_index)\n", " return F.log_softmax(x, dim=1)\n", "\n", "class GATModel(nn.Module):\n", " \"\"\"\n", " Graph Attention Network (GAT) implementation\n", " \n", " GAT Architecture Rationale:\n", " - Uses attention mechanism to weight neighbor contributions\n", " - Multi-head attention for learning diverse relationship types\n", " - More sophisticated than GCN/GraphSAGE but potentially more powerful\n", " \n", " Attention Benefits:\n", " - Learns which neighbors are most important dynamically\n", " - Provides interpretability through attention weights\n", " - Handles heterogeneous graphs better\n", " \n", " Multi-head Attention:\n", " - heads=8: Allows learning multiple types of relationships\n", " - Concatenated in hidden layers, averaged in final layer\n", " \"\"\"\n", " def __init__(self, num_features, hidden_dim, num_classes, num_layers=2, dropout=0.5, heads=8):\n", " super(GATModel, self).__init__()\n", " self.num_layers = num_layers\n", " self.dropout = dropout\n", " \n", " self.convs = nn.ModuleList()\n", " \n", " # First layer: input -> hidden with multi-head attention\n", " self.convs.append(GATConv(num_features, hidden_dim, heads=heads, dropout=dropout))\n", " \n", " # Hidden layers: concatenated heads -> hidden with multi-head attention \n", " for _ in range(num_layers - 2):\n", " # Input dimension is hidden_dim * heads due to concatenation\n", " self.convs.append(GATConv(hidden_dim * heads, hidden_dim, heads=heads, dropout=dropout))\n", " \n", " # Final layer: single head for classification (averages attention)\n", " self.convs.append(GATConv(hidden_dim * heads, num_classes, heads=1, dropout=dropout))\n", " \n", " logger.info(f\"GAT Model initialized with {num_features} input features, {hidden_dim} hidden dim, {num_classes} classes, {heads} attention heads\")\n", " \n", " def forward(self, x, edge_index, batch=None):\n", " \"\"\"\n", " Forward pass through GAT layers\n", " \n", " GAT Process:\n", " 1. Compute attention coefficients for each edge\n", " 2. Apply softmax to normalize attention weights\n", " 3. Weight neighbor features by attention coefficients\n", " 4. Aggregate weighted features\n", " \"\"\"\n", " # Process through attention layers\n", " for i, conv in enumerate(self.convs[:-1]):\n", " x = conv(x, edge_index) # Multi-head attention\n", " x = F.relu(x) # Activation after attention\n", " x = F.dropout(x, p=self.dropout, training=self.training)\n", " \n", " # Final attention layer (single head)\n", " x = self.convs[-1](x, edge_index)\n", " return F.log_softmax(x, dim=1)\n", "\n", "def load_and_explore_data():\n", " \"\"\"\n", " Load and analyze the Cora citation network dataset\n", " \n", " Cora Dataset Details:\n", " - Citation network of machine learning papers\n", " - 2708 nodes (papers), 10556 edges (citations)\n", " - 7 classes (research areas): Neural Networks, Rule Learning, etc.\n", " - 1433 features per node (bag-of-words from paper abstracts)\n", " - Semi-supervised learning setup: 140 training, 500 validation, 1000 test nodes\n", " \n", " Data Split Analysis:\n", " - Very small training set (5.2%) creates challenging learning scenario\n", " - Large test set (36.9%) provides reliable evaluation\n", " - Imbalanced split tests model's ability to generalize from limited data\n", " \"\"\"\n", " logger.info(\"Loading Cora dataset...\")\n", " \n", " # Load Cora dataset with feature normalization\n", " # NormalizeFeatures: scales node features to unit norm for stable training\n", " dataset = Planetoid(root='/tmp/Cora', name='Cora', transform=NormalizeFeatures())\n", " data = dataset[0] # Single graph in dataset\n", " \n", " # Log comprehensive dataset statistics\n", " logger.info(f\"Dataset: {dataset}\")\n", " logger.info(f\"Number of graphs: {len(dataset)}\")\n", " logger.info(f\"Number of features: {dataset.num_features}\")\n", " logger.info(f\"Number of classes: {dataset.num_classes}\")\n", " logger.info(f\"Number of nodes: {data.num_nodes}\")\n", " logger.info(f\"Number of edges: {data.num_edges}\")\n", " logger.info(f\"Average node degree: {data.num_edges / data.num_nodes:.2f}\")\n", " logger.info(f\"Training nodes: {data.train_mask.sum()}\")\n", " logger.info(f\"Validation nodes: {data.val_mask.sum()}\")\n", " logger.info(f\"Test nodes: {data.test_mask.sum()}\")\n", " \n", " # Calculate and log data split ratios\n", " train_ratio = data.train_mask.sum() / data.num_nodes\n", " val_ratio = data.val_mask.sum() / data.num_nodes\n", " test_ratio = data.test_mask.sum() / data.num_nodes\n", " logger.info(f\"Data split ratios - Train: {train_ratio:.3f}, Val: {val_ratio:.3f}, Test: {test_ratio:.3f}\")\n", " \n", " return dataset, data\n", "\n", "def create_graph_visualization(data, save_path='graph_visualization.png'):\n", " \"\"\"\n", " Create and save a visualization of the graph structure\n", " \n", " Visualization Strategy:\n", " - Spring layout: positions nodes to minimize edge crossings\n", " - Color-coded by node classes for pattern recognition\n", " - Small node size due to large number of nodes (2708)\n", " - High-resolution PNG for clear visualization\n", " \n", " Spring Layout Parameters:\n", " - k=0.5: Controls node spacing (smaller = more compact)\n", " - iterations=50: Layout optimization steps (more = better but slower)\n", " \"\"\"\n", " logger.info(\"Creating graph visualization...\")\n", " \n", " # Convert PyTorch tensors to numpy for NetworkX compatibility\n", " # Must move to CPU first due to MPS device limitations\n", " edge_index = data.edge_index.cpu().numpy()\n", " node_labels = data.y.cpu().numpy()\n", " \n", " # Create NetworkX graph from edge list\n", " G = nx.Graph()\n", " G.add_edges_from(edge_index.T) # Transpose to get (source, target) pairs\n", " \n", " # Create matplotlib figure with explicit axes for colorbar compatibility\n", " fig, ax = plt.subplots(figsize=(12, 8))\n", " \n", " # Compute spring layout positions for aesthetic node placement\n", " pos = nx.spring_layout(G, k=0.5, iterations=50)\n", " \n", " # Draw graph with color-coded nodes\n", " nx.draw(G, pos, node_color=node_labels, node_size=20, \n", " with_labels=False, cmap='Set3', alpha=0.7, ax=ax)\n", " \n", " ax.set_title(\"Cora Citation Network Visualization\")\n", " \n", " # Create colorbar with proper normalization\n", " # ScalarMappable maps node class indices to colors\n", " sm = plt.cm.ScalarMappable(cmap='Set3', norm=plt.Normalize(vmin=node_labels.min(), vmax=node_labels.max()))\n", " sm.set_array([]) # Required for colorbar creation\n", " plt.colorbar(sm, ax=ax, label='Node Classes')\n", " \n", " # Save high-resolution image\n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close() # Free memory\n", " \n", " logger.info(f\"Graph visualization saved to {save_path}\")\n", "\n", "def train_model(model, data, optimizer, criterion, device):\n", " \"\"\"\n", " Execute one training epoch\n", " \n", " Training Process:\n", " 1. Set model to training mode (enables dropout)\n", " 2. Zero gradients from previous step\n", " 3. Forward pass through model\n", " 4. Compute loss only on training nodes\n", " 5. Backpropagate gradients\n", " 6. Update model parameters\n", " 7. Compute training accuracy for monitoring\n", " \n", " Loss Function Choice:\n", " - NLLLoss: Negative Log-Likelihood Loss\n", " - Works with log_softmax output from models\n", " - Equivalent to CrossEntropyLoss but with log probabilities\n", " \"\"\"\n", " model.train() # Enable dropout and batch normalization training mode\n", " optimizer.zero_grad() # Clear gradients from previous iteration\n", " \n", " # Forward pass: compute predictions for all nodes\n", " out = model(data.x, data.edge_index)\n", " \n", " # Compute loss only on training nodes (semi-supervised learning)\n", " loss = criterion(out[data.train_mask], data.y[data.train_mask])\n", " \n", " # Backward pass: compute gradients\n", " loss.backward()\n", " \n", " # Update model parameters\n", " optimizer.step()\n", " \n", " # Compute training accuracy (no gradients needed)\n", " with torch.no_grad():\n", " pred = out[data.train_mask].argmax(dim=1) # Get predicted classes\n", " train_acc = accuracy_score(data.y[data.train_mask].cpu(), pred.cpu())\n", " \n", " return loss.item(), train_acc\n", "\n", "def validate_model(model, data, criterion, device):\n", " \"\"\"\n", " Evaluate model on validation set\n", " \n", " Validation Purpose:\n", " - Monitor overfitting during training\n", " - Early stopping criterion\n", " - Hyperparameter selection\n", " \n", " Key Differences from Training:\n", " - eval() mode: disables dropout, fixes batch normalization\n", " - no_grad(): disables gradient computation for efficiency\n", " - Only forward pass, no parameter updates\n", " \"\"\"\n", " model.eval() # Disable dropout and set batch normalization to eval mode\n", " with torch.no_grad(): # Disable gradient computation for efficiency\n", " # Forward pass on entire graph\n", " out = model(data.x, data.edge_index)\n", " \n", " # Compute validation loss and accuracy\n", " val_loss = criterion(out[data.val_mask], data.y[data.val_mask])\n", " pred = out[data.val_mask].argmax(dim=1)\n", " val_acc = accuracy_score(data.y[data.val_mask].cpu(), pred.cpu())\n", " \n", " return val_loss.item(), val_acc\n", "\n", "def test_model(model, data, device):\n", " \"\"\"\n", " Comprehensive evaluation on test set\n", " \n", " Test Evaluation Includes:\n", " - Accuracy: Overall classification performance\n", " - Classification report: Per-class precision, recall, F1-score\n", " - Confusion matrix: Detailed error analysis\n", " - Node embeddings: For visualization and analysis\n", " \n", " Why Comprehensive Evaluation:\n", " - Test set is large (1000 nodes) - reliable statistics\n", " - Multiple metrics reveal different aspects of performance\n", " - Embeddings enable understanding of learned representations\n", " \"\"\"\n", " model.eval()\n", " with torch.no_grad():\n", " # Get model outputs for all nodes\n", " out = model(data.x, data.edge_index)\n", " \n", " # Compute test accuracy\n", " pred = out[data.test_mask].argmax(dim=1)\n", " test_acc = accuracy_score(data.y[data.test_mask].cpu(), pred.cpu())\n", " \n", " # Prepare data for detailed evaluation\n", " y_true = data.y[data.test_mask].cpu().numpy()\n", " y_pred = pred.cpu().numpy()\n", " \n", " # Generate comprehensive evaluation metrics\n", " report = classification_report(y_true, y_pred, output_dict=True)\n", " conf_matrix = confusion_matrix(y_true, y_pred)\n", " \n", " return test_acc, report, conf_matrix, out\n", "\n", "def train_and_evaluate_model(model_class, model_name, data, device, config):\n", " \"\"\"\n", " Complete training pipeline for a single model\n", " \n", " Training Strategy Rationale:\n", " - Adam optimizer: adaptive learning rates, good default choice\n", " - Learning rate 0.001: conservative to ensure stable learning\n", " - Weight decay 5e-4: L2 regularization to prevent overfitting\n", " - Early stopping: prevents overfitting, saves best model\n", " \n", " Hyperparameter Choices Explained:\n", " - hidden_dim=32: Small enough for limited training data (140 nodes)\n", " - dropout=0.5: Strong regularization due to small training set\n", " - patience=20: Allows model time to improve before stopping\n", " \n", " Early Stopping Logic:\n", " - Monitor validation accuracy (primary metric)\n", " - Save model when validation accuracy improves\n", " - Stop training if no improvement for 'patience' epochs\n", " - Load best model for final evaluation\n", " \"\"\"\n", " logger.info(f\"Training {model_name} model...\")\n", " \n", " # Initialize model with appropriate architecture\n", " if model_name == 'GAT':\n", " # GAT requires additional attention heads parameter\n", " model = model_class(\n", " num_features=data.num_features,\n", " hidden_dim=config['hidden_dim'],\n", " num_classes=data.y.max().item() + 1, # Convert to number of classes\n", " num_layers=config['num_layers'],\n", " dropout=config['dropout'],\n", " heads=config['attention_heads']\n", " ).to(device)\n", " else:\n", " # Standard GCN and GraphSAGE initialization\n", " model = model_class(\n", " num_features=data.num_features,\n", " hidden_dim=config['hidden_dim'],\n", " num_classes=data.y.max().item() + 1,\n", " num_layers=config['num_layers'],\n", " dropout=config['dropout']\n", " ).to(device)\n", " \n", " # Configure optimizer and loss function\n", " # Adam: adaptive learning rate, momentum, good default\n", " # Weight decay: L2 regularization to prevent overfitting\n", " optimizer = optim.Adam(model.parameters(), lr=config['learning_rate'], weight_decay=config['weight_decay'])\n", " criterion = nn.NLLLoss() # Negative log-likelihood for classification\n", " \n", " # Log model complexity\n", " logger.info(f\"Model parameters: {sum(p.numel() for p in model.parameters()):,}\")\n", " \n", " # Training tracking variables\n", " train_losses, train_accs = [], []\n", " val_losses, val_accs = [], []\n", " best_val_acc = 0\n", " patience_counter = 0\n", " \n", " # Training loop with early stopping\n", " for epoch in range(config['epochs']):\n", " # Train for one epoch\n", " train_loss, train_acc = train_model(model, data, optimizer, criterion, device)\n", " \n", " # Validate current model\n", " val_loss, val_acc = validate_model(model, data, criterion, device)\n", " \n", " # Store metrics for plotting\n", " train_losses.append(train_loss)\n", " train_accs.append(train_acc)\n", " val_losses.append(val_loss)\n", " val_accs.append(val_acc)\n", " \n", " # Early stopping and model saving logic\n", " if val_acc > best_val_acc:\n", " best_val_acc = val_acc\n", " patience_counter = 0\n", " # Save best model state\n", " torch.save(model.state_dict(), f'best_{model_name.lower()}_model.pth')\n", " else:\n", " patience_counter += 1\n", " \n", " # Periodic progress logging (every 20 epochs)\n", " if (epoch + 1) % 20 == 0:\n", " logger.info(f\"Epoch {epoch+1}/{config['epochs']} - \"\n", " f\"Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, \"\n", " f\"Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}\")\n", " \n", " # Early stopping check\n", " if patience_counter >= config['patience']:\n", " logger.info(f\"Early stopping at epoch {epoch+1}\")\n", " break\n", " \n", " # Load best model for final evaluation\n", " model.load_state_dict(torch.load(f'best_{model_name.lower()}_model.pth'))\n", " \n", " # Comprehensive test evaluation\n", " test_acc, report, conf_matrix, embeddings = test_model(model, data, device)\n", " \n", " logger.info(f\"{model_name} Final Test Accuracy: {test_acc:.4f}\")\n", " \n", " # Return complete training results\n", " return {\n", " 'model': model,\n", " 'train_losses': train_losses,\n", " 'train_accs': train_accs,\n", " 'val_losses': val_losses,\n", " 'val_accs': val_accs,\n", " 'test_acc': test_acc,\n", " 'classification_report': report,\n", " 'confusion_matrix': conf_matrix,\n", " 'embeddings': embeddings\n", " }\n", "\n", "def create_training_plots(results, save_path='training_curves.png'):\n", " \"\"\"\n", " Generate comprehensive training visualization\n", " \n", " Visualization Design:\n", " - 2x3 subplot grid: loss and accuracy for each model\n", " - Separate train/validation curves: monitor overfitting\n", " - Different colors per model: easy comparison\n", " - Grid lines: easier value reading\n", " \n", " Plot Analysis:\n", " - Loss curves: should decrease and converge\n", " - Accuracy curves: should increase and plateau\n", " - Gap between train/val: indicates overfitting\n", " \"\"\"\n", " logger.info(\"Creating training curves...\")\n", " \n", " # Create subplot grid: 2 rows (loss, accuracy) x 3 columns (models)\n", " fig, axes = plt.subplots(2, 3, figsize=(18, 12))\n", " \n", " model_names = list(results.keys())\n", " colors = ['blue', 'red', 'green'] # Distinct colors for each model\n", " \n", " # Plot training curves for each model\n", " for i, (model_name, color) in enumerate(zip(model_names, colors)):\n", " result = results[model_name]\n", " \n", " # Loss curves (top row)\n", " axes[0, i].plot(result['train_losses'], color=color, label='Train Loss')\n", " axes[0, i].plot(result['val_losses'], color=color, linestyle='--', label='Val Loss')\n", " axes[0, i].set_title(f'{model_name} - Loss Curves')\n", " axes[0, i].set_xlabel('Epoch')\n", " axes[0, i].set_ylabel('Loss')\n", " axes[0, i].legend()\n", " axes[0, i].grid(True) # Add grid for easier reading\n", " \n", " # Accuracy curves (bottom row)\n", " axes[1, i].plot(result['train_accs'], color=color, label='Train Acc')\n", " axes[1, i].plot(result['val_accs'], color=color, linestyle='--', label='Val Acc')\n", " axes[1, i].set_title(f'{model_name} - Accuracy Curves')\n", " axes[1, i].set_xlabel('Epoch')\n", " axes[1, i].set_ylabel('Accuracy')\n", " axes[1, i].legend()\n", " axes[1, i].grid(True)\n", " \n", " # Save high-resolution figure\n", " plt.tight_layout() # Prevent subplot overlap\n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close() # Free memory\n", " \n", " logger.info(f\"Training curves saved to {save_path}\")\n", "\n", "def create_embeddings_visualization(results, data, save_path='embeddings_tsne.png'):\n", " \"\"\"\n", " Visualize learned node embeddings using t-SNE\n", " \n", " t-SNE Visualization Purpose:\n", " - Reduce high-dimensional embeddings to 2D for visualization\n", " - Preserve local neighborhood structure\n", " - Reveal clustering patterns learned by models\n", " \n", " t-SNE Parameters:\n", " - n_components=2: 2D visualization\n", " - random_state=42: reproducible results\n", " - perplexity=30: good default for medium-sized datasets\n", " \n", " Interpretation:\n", " - Well-separated clusters: good class separation\n", " - Mixed colors: challenging classification regions\n", " - Tight clusters: strong within-class similarity\n", " \"\"\"\n", " logger.info(\"Creating embeddings visualization...\")\n", " \n", " # Create subplot for each model's embeddings\n", " fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n", " \n", " model_names = list(results.keys())\n", " \n", " for i, model_name in enumerate(model_names):\n", " # Get node embeddings (model outputs) and labels\n", " embeddings = results[model_name]['embeddings'].cpu().numpy()\n", " labels = data.y.cpu().numpy()\n", " \n", " # Apply t-SNE dimensionality reduction\n", " # perplexity=30: considers 30 nearest neighbors for embedding\n", " tsne = TSNE(n_components=2, random_state=42, perplexity=30)\n", " embeddings_2d = tsne.fit_transform(embeddings)\n", " \n", " # Create scatter plot colored by true node classes\n", " scatter = axes[i].scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], \n", " c=labels, cmap='Set3', alpha=0.7, s=20)\n", " axes[i].set_title(f'{model_name} - Node Embeddings (t-SNE)')\n", " axes[i].set_xlabel('t-SNE 1')\n", " axes[i].set_ylabel('t-SNE 2')\n", " \n", " # Add colorbar for class labels\n", " plt.colorbar(scatter, ax=axes[i])\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_path, dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " logger.info(f\"Embeddings visualization saved to {save_path}\")\n", "\n", "def save_results_summary(results, config, save_path='results_summary.json'):\n", " \"\"\"\n", " Save comprehensive experiment results to JSON\n", " \n", " Results Structure:\n", " - Experiment configuration: all hyperparameters used\n", " - Model performance: comprehensive metrics for each model\n", " - Timestamp: when experiment was conducted\n", " \n", " Metrics Saved:\n", " - Test accuracy: primary evaluation metric\n", " - Training/validation accuracy: overfitting analysis\n", " - Precision/recall/F1: detailed performance analysis\n", " \n", " JSON Format Benefits:\n", " - Human readable\n", " - Easy to parse programmatically\n", " - Version control friendly\n", " - Can be loaded into analysis tools\n", " \"\"\"\n", " logger.info(\"Saving results summary...\")\n", " \n", " # Structure comprehensive results dictionary\n", " summary = {\n", " 'experiment_config': config, # All hyperparameters\n", " 'model_performance': {}, # Per-model metrics\n", " 'timestamp': datetime.now().isoformat() # When experiment ran\n", " }\n", " \n", " # Extract key metrics for each model\n", " for model_name, result in results.items():\n", " summary['model_performance'][model_name] = {\n", " 'test_accuracy': float(result['test_acc']),\n", " 'final_train_accuracy': float(result['train_accs'][-1]),\n", " 'final_val_accuracy': float(result['val_accs'][-1]),\n", " 'best_val_accuracy': float(max(result['val_accs'])),\n", " 'precision_macro': float(result['classification_report']['macro avg']['precision']),\n", " 'recall_macro': float(result['classification_report']['macro avg']['recall']),\n", " 'f1_macro': float(result['classification_report']['macro avg']['f1-score'])\n", " }\n", " \n", " # Save to JSON file with proper formatting\n", " with open(save_path, 'w') as f:\n", " json.dump(summary, f, indent=2) # indent=2 for readability\n", " \n", " logger.info(f\"Results summary saved to {save_path}\")\n", "\n", "def main():\n", " \"\"\"\n", " Main training pipeline orchestrating the entire experiment\n", " \n", " Pipeline Steps:\n", " 1. Device setup: Use best available accelerator (MPS > CUDA > CPU)\n", " 2. Data loading: Load and analyze Cora dataset\n", " 3. Visualization: Create graph structure plot\n", " 4. Model training: Train all three GNN architectures\n", " 5. Evaluation: Compare model performances\n", " 6. Artifact saving: Save all models, plots, and results\n", " \n", " Device Selection Logic:\n", " - MPS (Apple Silicon): Fast on M1/M2/M3/M4 Macs\n", " - CUDA (NVIDIA GPU): Standard for deep learning\n", " - CPU: Fallback for compatibility\n", " \n", " Configuration Rationale:\n", " - Conservative hyperparameters for stable learning\n", " - Early stopping to prevent overfitting\n", " - Comprehensive logging for debugging\n", " \"\"\"\n", " logger.info(\"Starting GNN training pipeline...\")\n", " \n", " # Determine best available compute device\n", " device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", " logger.info(f\"Using device: {device}\")\n", " \n", " # Check for Apple Silicon acceleration\n", " if torch.backends.mps.is_available():\n", " device = torch.device('mps')\n", " logger.info(\"Using Apple Silicon MPS acceleration\")\n", " \n", " # Load dataset and move to compute device\n", " dataset, data = load_and_explore_data()\n", " data = data.to(device)\n", " \n", " # Create graph visualization for analysis\n", " create_graph_visualization(data)\n", " \n", " # Define training configuration\n", " # These hyperparameters were chosen based on:\n", " # - Small training set (140 nodes) requires regularization\n", " # - Graph size (2708 nodes) allows modest model complexity\n", " # - Citation network characteristics suggest 2-layer models sufficient\n", " config = {\n", " 'hidden_dim': 32, # Small to prevent overfitting\n", " 'num_layers': 2, # Avoid over-smoothing\n", " 'dropout': 0.5, # Strong regularization\n", " 'learning_rate': 0.001, # Conservative learning rate\n", " 'weight_decay': 5e-4, # L2 regularization\n", " 'epochs': 200, # Maximum training epochs\n", " 'patience': 20, # Early stopping patience\n", " 'attention_heads': 8 # Multi-head attention for GAT\n", " }\n", " \n", " logger.info(f\"Training configuration: {config}\")\n", " \n", " # Define models to train and compare\n", " models = {\n", " 'GCN': GCNModel, # Spectral graph convolution baseline\n", " 'GraphSAGE': GraphSAGEModel, # Sampling-based approach\n", " 'GAT': GATModel # Attention-based method\n", " }\n", " \n", " # Train each model and collect results\n", " results = {}\n", " \n", " for model_name, model_class in models.items():\n", " logger.info(f\"\\n{'='*50}\")\n", " logger.info(f\"Training {model_name}\")\n", " logger.info(f\"{'='*50}\")\n", "\n", " # Train model with comprehensive evaluation\n", " result = train_and_evaluate_model(model_class, model_name, data, device, config)\n", " results[model_name] = result\n", " \n", " # Save complete model for future use\n", " # pickle preserves entire model including architecture\n", " with open(f'{model_name.lower()}_full_model.pkl', 'wb') as f:\n", " pickle.dump(result['model'], f)\n", " \n", " logger.info(f\"{model_name} training completed and saved\")\n", "\n", "# Generate comprehensive visualizations\n", "create_training_plots(results)\n", "create_embeddings_visualization(results, data)\n", "save_results_summary(results, config)\n", "\n", "# Final results analysis and comparison\n", "logger.info(\"\\n\" + \"=\"*60)\n", "logger.info(\"FINAL RESULTS COMPARISON\")\n", "logger.info(\"=\"*60)\n", "\n", "# Display test accuracies for easy comparison\n", "for model_name, result in results.items():\n", " logger.info(f\"{model_name:12} - Test Accuracy: {result['test_acc']:.4f}\")\n", "\n", "# Identify best performing model\n", "best_model = max(results.items(), key=lambda x: x[1]['test_acc'])\n", "logger.info(f\"\\nBest performing model: {best_model[0]} with accuracy: {best_model[1]['test_acc']:.4f}\")\n", "\n", "# Summary of saved artifacts\n", "logger.info(\"\\nAll training artifacts saved:\")\n", "logger.info(\"- Model checkpoints: best_*_model.pth\") # PyTorch state dicts\n", "logger.info(\"- Full models: *_full_model.pkl\") # Complete model objects\n", "logger.info(\"- Training curves: training_curves.png\") # Loss/accuracy plots\n", "logger.info(\"- Embeddings visualization: embeddings_tsne.png\") # t-SNE plots\n", "logger.info(\"- Graph visualization: graph_visualization.png\") # Network structure\n", "logger.info(\"- Results summary: results_summary.json\") # Comprehensive metrics\n", "logger.info(\"- Training logs: gnn_training.log\") # Complete execution log\n", "\n", "logger.info(\"\\nGNN training pipeline completed successfully!\")" ] }, { "cell_type": "code", "execution_count": null, "id": "42d83e1f-ef38-427d-8cc2-31bf92d0ec67", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 5 }