tahamajs/Sysmem2_in_AI / ComputerAssignments /CA10_knowledge_graphs /notebooks /add_remaining_sections.py
| #!/usr/bin/env python3 | |
| """ | |
| Script to add remaining comprehensive sections to the GNN notebook | |
| """ | |
| import json | |
| def create_section2_markdown(): | |
| """Create comprehensive Section 2 markdown""" | |
| return """## 2. Create Knowledge Graph <a id="section2"></a> | |
| ### 2.1 Knowledge Graph Construction Process | |
| In this section, we create a sample knowledge graph to demonstrate GNN capabilities. The construction process involves: | |
| **1. Entity Definition:** | |
| - Scientific entities (persons, theories, institutions) | |
| - Temporal entities (events, time periods) | |
| - Conceptual entities (fields of study, methodologies) | |
| **2. Relation Schema:** | |
| - Hierarchical relations (subclass_of, part_of) | |
| - Associative relations (related_to, influenced_by) | |
| - Temporal relations (discovered, published, occurred) | |
| - Social relations (collaborated_with, mentor_of) | |
| **3. Triple Generation:** | |
| Each triple represents a fact: (subject, predicate, object) | |
| - Example: (Einstein, discovered, Relativity) | |
| - Directionality: Some relations are asymmetric | |
| - Completeness: Real KGs are often incomplete | |
| ### 2.2 Knowledge Graph Statistics and Characteristics | |
| **Important Graph Metrics:** | |
| 1. **Number of Entities (|V|):** | |
| - Represents the scale of the graph | |
| - Affects model complexity and training time | |
| 2. **Number of Relations (|R|):** | |
| - Indicates relational diversity | |
| - Critical for R-GCN architecture choices | |
| 3. **Number of Triples (|E|):** | |
| - Total facts in the knowledge base | |
| - Determines training data size | |
| 4. **Average Degree:** | |
| - $\\bar{d} = \\frac{2|E|}{|V|}$ for undirected graphs | |
| - Indicates graph connectivity | |
| 5. **Graph Density:** | |
| - $\\rho = \\frac{|E|}{|V|(|V|-1)/2}$ | |
| - Sparse graphs: $\\rho \\ll 1$ | |
| ### 2.3 PyTorch Geometric Conversion | |
| **Conversion Process:** | |
| The function `create_pyg_data_from_kg()` transforms our KG into PyTorch Geometric format: | |
| **Step 1: Entity Indexing** | |
| ```python | |
| entity_to_idx = {entity_id: idx for idx, entity_id in enumerate(kg.entities)} | |
| ``` | |
| **Step 2: Edge List Construction** | |
| ```python | |
| edge_index = [[src_idx, ...], [dst_idx, ...]] # Shape: [2, num_edges] | |
| ``` | |
| **Step 3: Feature Initialization** | |
| - Random initialization: $X \\sim \\mathcal{N}(0, 1)$ | |
| - One-hot encoding: $X \\in \\{0, 1\\}^{|V| \\times |V|}$ | |
| - Pre-trained embeddings: $X = \\text{Bert}(\\text{entity\\_names})$ | |
| **Step 4: Edge Type Encoding** | |
| ```python | |
| edge_type = [relation_to_idx[relation] for each edge] | |
| ``` | |
| ### 2.4 Data Structure Advantages | |
| **Why COO Format?** | |
| The Coordinate (COO) format offers: | |
| - **Sparsity**: Only stores non-zero entries | |
| - **Efficiency**: Fast sparse matrix operations | |
| - **GPU-friendly**: Optimized for CUDA kernels | |
| - **Flexibility**: Easy to add/remove edges | |
| **Memory Comparison:** | |
| - Dense adjacency: $O(|V|^2)$ - infeasible for large graphs | |
| - COO format: $O(|E|)$ - scales to billions of edges | |
| **Example:** | |
| ``` | |
| Graph with 1M nodes, 10M edges: | |
| Dense: 1M × 1M = 1TB (if 1 byte/entry) | |
| COO: 10M × 2 = 80MB (if 4 bytes/index) | |
| ```""" | |
| def create_training_section_markdown(): | |
| """Create comprehensive training section""" | |
| return """### 7.1 Link Prediction Task Formulation | |
| **Link Prediction** is a fundamental task in knowledge graph reasoning: | |
| **Problem:** Given an incomplete triple $(h, r, ?)$ or $(?, r, t)$, predict the missing entity. | |
| **Mathematically:** | |
| $$\\text{score}(h, r, t) = f_\\theta(e_h, e_r, e_t)$$ | |
| Where: | |
| - $e_h, e_t$: Entity embeddings from GNN encoder | |
| - $e_r$: Relation embedding | |
| - $f_\\theta$: Scoring function (learned) | |
| - Higher score → more likely to be a true fact | |
| **Common Scoring Functions:** | |
| 1. **DistMult (Bilinear):** | |
| $$\\text{score}(h, r, t) = e_h^T \\text{diag}(e_r) e_t$$ | |
| 2. **TransE (Translation-based):** | |
| $$\\text{score}(h, r, t) = -\\|e_h + e_r - e_t\\|$$ | |
| 3. **Dot Product (Simple):** | |
| $$\\text{score}(h, r, t) = \\sigma(e_h^T e_t)$$ | |
| ### 7.2 Training Data Preparation | |
| **Positive Samples:** | |
| - Actual triples from the knowledge graph | |
| - Label: 1 (true fact) | |
| **Negative Samples:** | |
| - Corrupted triples (random entity substitution) | |
| - Label: 0 (false fact) | |
| - Generation strategies: | |
| - **Head corruption**: $(h', r, t)$ where $h' \\neq h$ | |
| - **Tail corruption**: $(h, r, t')$ where $t' \\neq t$ | |
| - **Random corruption**: Replace either head or tail | |
| **Negative Sampling Ratio:** | |
| - Typical: 1:1 to 1:5 (positive:negative) | |
| - More negatives → better discrimination | |
| - Too many → class imbalance | |
| ### 7.3 Loss Functions for Link Prediction | |
| **1. Binary Cross-Entropy Loss:** | |
| $$\\mathcal{L}_{BCE} = -\\frac{1}{N}\\sum_{i=1}^N [y_i \\log(\\hat{y}_i) + (1-y_i)\\log(1-\\hat{y}_i)]$$ | |
| - Standard for binary classification | |
| - Works well with sigmoid activation | |
| - Numerical stability with BCEWithLogitsLoss | |
| **2. Margin-based Loss:** | |
| $$\\mathcal{L}_{margin} = \\sum_{(h,r,t) \\in \\mathcal{T}^+} \\sum_{(h',r,t') \\in \\mathcal{T}^-} [\\gamma + \\text{score}(h',r,t') - \\text{score}(h,r,t)]_+$$ | |
| Where $[x]_+ = \\max(0, x)$ and $\\gamma$ is the margin. | |
| **3. Softmax Cross-Entropy:** | |
| $$\\mathcal{L}_{softmax} = -\\log \\frac{\\exp(\\text{score}(h,r,t))}{\\sum_{t' \\in \\mathcal{E}} \\exp(\\text{score}(h,r,t'))}$$ | |
| - Normalizes over all possible tails | |
| - Computationally expensive for large entity sets | |
| - Often use negative sampling approximation | |
| ### 7.4 Training Procedure and Optimization | |
| **Standard Training Loop:** | |
| ```python | |
| for epoch in range(num_epochs): | |
| # 1. Forward pass through GNN | |
| embeddings = model(node_features, edge_index) | |
| # 2. Compute scores for positive and negative samples | |
| pos_scores = score_function(pos_triples, embeddings) | |
| neg_scores = score_function(neg_triples, embeddings) | |
| # 3. Compute loss | |
| loss = criterion(pos_scores, neg_scores) | |
| # 4. Backpropagation | |
| optimizer.zero_grad() | |
| loss.backward() | |
| # 5. Update parameters | |
| optimizer.step() | |
| ``` | |
| **Optimization Considerations:** | |
| 1. **Learning Rate:** | |
| - Start: 0.001-0.01 | |
| - Scheduler: ReduceLROnPlateau or CosineAnnealing | |
| - Warmup: Gradually increase LR in first epochs | |
| 2. **Optimizer Choice:** | |
| - **Adam**: Adaptive learning rates, works well in practice | |
| - **AdamW**: Adam with decoupled weight decay | |
| - **SGD with momentum**: Sometimes more stable | |
| 3. **Weight Decay (L2 Regularization):** | |
| - Typical: 1e-5 to 1e-3 | |
| - Prevents overfitting | |
| - Essential for small datasets | |
| 4. **Gradient Clipping:** | |
| - Clip by norm: `torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)` | |
| - Prevents exploding gradients | |
| - Important for deep GNNs | |
| ### 7.5 Evaluation Metrics | |
| **Classification Metrics:** | |
| 1. **Accuracy:** | |
| $$\\text{Acc} = \\frac{TP + TN}{TP + TN + FP + FN}$$ | |
| 2. **Precision:** | |
| $$\\text{Prec} = \\frac{TP}{TP + FP}$$ | |
| 3. **Recall:** | |
| $$\\text{Rec} = \\frac{TP}{TP + FN}$$ | |
| 4. **F1-Score:** | |
| $$F_1 = 2 \\cdot \\frac{\\text{Prec} \\cdot \\text{Rec}}{\\text{Prec} + \\text{Rec}}$$ | |
| **Ranking Metrics:** | |
| 1. **Mean Rank (MR):** | |
| - Average rank of correct entity | |
| - Lower is better | |
| - Sensitive to outliers | |
| 2. **Mean Reciprocal Rank (MRR):** | |
| $$\\text{MRR} = \\frac{1}{|Q|}\\sum_{i=1}^{|Q|} \\frac{1}{\\text{rank}_i}$$ | |
| - More robust than MR | |
| - Range: [0, 1], higher is better | |
| 3. **Hits@K:** | |
| $$\\text{Hits@K} = \\frac{\\#\\{\\text{queries with correct answer in top K}\\}}{|Q|}$$ | |
| - Percentage of queries with answer in top K | |
| - Common: K ∈ {1, 3, 10} | |
| ### 7.6 Overfitting Prevention Strategies | |
| **1. Dropout:** | |
| - Apply to node features: `F.dropout(x, p=0.5, training=True)` | |
| - Apply to attention weights (GAT) | |
| - Typical rate: 0.3-0.6 | |
| **2. Early Stopping:** | |
| ```python | |
| if val_loss < best_val_loss: | |
| best_val_loss = val_loss | |
| patience_counter = 0 | |
| save_model() | |
| else: | |
| patience_counter += 1 | |
| if patience_counter >= patience: | |
| break # Stop training | |
| ``` | |
| **3. Data Augmentation:** | |
| - Triple augmentation: Add inverse relations | |
| - Entity augmentation: Entity type information | |
| - Subgraph sampling: Train on graph subsets | |
| **4. Regularization:** | |
| - L2 weight decay | |
| - Batch normalization | |
| - Layer normalization | |
| ### 7.7 Best Practices for GNN Training | |
| **1. Data Splitting:** | |
| - Train: 70-80% | |
| - Validation: 10-15% | |
| - Test: 10-15% | |
| - Ensure no information leakage | |
| **2. Batch Size Selection:** | |
| - Small graphs: Full-batch training | |
| - Large graphs: Mini-batch with sampling | |
| - Typical: 32-256 for mini-batch | |
| **3. Model Capacity:** | |
| - Start small, increase if underfitting | |
| - Monitor train/val gap | |
| - Consider parameter count vs. data size | |
| **4. Convergence Monitoring:** | |
| - Plot train/val loss curves | |
| - Check gradient norms | |
| - Monitor embedding magnitudes | |
| **5. Reproducibility:** | |
| ```python | |
| torch.manual_seed(42) | |
| np.random.seed(42) | |
| random.seed(42) | |
| torch.backends.cudnn.deterministic = True | |
| ```""" | |
| def create_visualization_section(): | |
| """Create comprehensive visualization section""" | |
| return """### 9.1 Dimensionality Reduction for Visualization | |
| **Challenge:** GNN embeddings are high-dimensional (64-256 dims), but we can only visualize 2D/3D. | |
| **Solution:** Dimensionality reduction techniques project high-dim embeddings to low-dim space while preserving structure. | |
| ### 9.2 t-SNE: t-Distributed Stochastic Neighbor Embedding | |
| **Algorithm Overview:** | |
| t-SNE [9] creates a 2D map where similar entities are close and dissimilar entities are far apart. | |
| **Mathematical Formulation:** | |
| **Step 1: Compute High-Dimensional Similarities** | |
| $$p_{j|i} = \\frac{\\exp(-\\|x_i - x_j\\|^2 / 2\\sigma_i^2)}{\\sum_{k \\neq i} \\exp(-\\|x_i - x_k\\|^2 / 2\\sigma_i^2)}$$ | |
| $$p_{ij} = \\frac{p_{j|i} + p_{i|j}}{2N}$$ | |
| **Step 2: Compute Low-Dimensional Similarities** | |
| $$q_{ij} = \\frac{(1 + \\|y_i - y_j\\|^2)^{-1}}{\\sum_{k \\neq l} (1 + \\|y_k - y_l\\|^2)^{-1}}$$ | |
| **Step 3: Minimize KL Divergence** | |
| $$\\mathcal{L} = \\sum_i KL(P_i \\| Q_i) = \\sum_i \\sum_j p_{ij} \\log \\frac{p_{ij}}{q_{ij}}$$ | |
| **Key Hyperparameters:** | |
| 1. **Perplexity (5-50):** | |
| - Balances local vs. global structure | |
| - Roughly: number of nearest neighbors | |
| - Larger datasets → higher perplexity | |
| 2. **Learning Rate (10-1000):** | |
| - Controls optimization step size | |
| - Too high → unstable | |
| - Too low → slow convergence | |
| 3. **Number of Iterations (1000-5000):** | |
| - More iterations → better convergence | |
| - Diminishing returns after convergence | |
| **Advantages:** | |
| ✅ Preserves local structure well | |
| ✅ Reveals clusters and patterns | |
| ✅ Works well for visualization | |
| **Limitations:** | |
| ❌ Non-deterministic (different runs differ) | |
| ❌ Doesn't preserve global structure | |
| ❌ Slow for large datasets | |
| ### 9.3 Alternative Visualization Techniques | |
| **1. UMAP (Uniform Manifold Approximation and Projection):** | |
| $$\\mathcal{L} = \\sum_{i,j} w_{ij}^{high} \\log\\left(\\frac{w_{ij}^{high}}{w_{ij}^{low}}\\right) + (1-w_{ij}^{high})\\log\\left(\\frac{1-w_{ij}^{high}}{1-w_{ij}^{low}}\\right)$$ | |
| **Advantages over t-SNE:** | |
| - Faster for large datasets | |
| - Better preserves global structure | |
| - Deterministic with fixed seed | |
| - Can project new points | |
| **2. PCA (Principal Component Analysis):** | |
| $$y = X W_{top-k}$$ | |
| Where $W_{top-k}$ are the top-k eigenvectors of the covariance matrix. | |
| **Advantages:** | |
| - Fast and deterministic | |
| - Preserves global structure | |
| - Linear projection | |
| **Disadvantages:** | |
| - Only captures linear relationships | |
| - May miss complex patterns | |
| **3. Graph Layout Algorithms:** | |
| - **Force-directed**: Nodes repel, edges attract | |
| - **Spectral layout**: Based on graph Laplacian eigenvectors | |
| - **Community-based**: Cluster nodes by communities | |
| ### 9.4 Interpreting Visualization Results | |
| **What to Look For:** | |
| 1. **Clusters:** | |
| - Do similar entities group together? | |
| - Are clusters semantically meaningful? | |
| - Example: All "scientists" in one region | |
| 2. **Separation:** | |
| - Are different entity types well-separated? | |
| - Clear boundaries indicate good discriminative features | |
| 3. **Outliers:** | |
| - Isolated points may indicate: | |
| - Unique entities | |
| - Noise in data | |
| - Model errors | |
| 4. **Continuity:** | |
| - Smooth transitions between clusters | |
| - Indicates learned hierarchical structure | |
| ### 9.5 Attention Weight Visualization (GAT-specific) | |
| **Attention as Interpretability:** | |
| GAT's attention weights $\\alpha_{vu}$ indicate edge importance. | |
| **Visualization Approaches:** | |
| **1. Attention Heatmap:** | |
| ``` | |
| u1 u2 u3 u4 | |
| v1 [0.4 0.1 0.3 0.2] | |
| v2 [0.2 0.5 0.1 0.2] | |
| ... | |
| ``` | |
| **2. Edge Width Visualization:** | |
| - Thicker edges → higher attention | |
| - Color intensity → attention magnitude | |
| **3. Attention Distribution Analysis:** | |
| ```python | |
| # Plot attention histogram | |
| plt.hist(alpha.flatten(), bins=50) | |
| plt.xlabel('Attention Weight') | |
| plt.ylabel('Frequency') | |
| ``` | |
| **Interpretation:** | |
| - Uniform distribution → similar to GCN (all edges equal) | |
| - Skewed distribution → model learned selectivity | |
| - Peaks indicate common attention patterns | |
| ### 9.6 Embedding Quality Assessment | |
| **Quantitative Metrics:** | |
| **1. Clustering Coefficient:** | |
| $$C = \\frac{\\text{# of triangles}}{\\text{# of connected triples}}$$ | |
| **2. Silhouette Score:** | |
| $$s(i) = \\frac{b(i) - a(i)}{\\max(a(i), b(i))}$$ | |
| Where: | |
| - $a(i)$: Mean distance to same cluster | |
| - $b(i)$: Mean distance to nearest other cluster | |
| - Range: [-1, 1], higher is better | |
| **3. Homogeneity and Completeness:** | |
| - Homogeneity: Each cluster contains only one class | |
| - Completeness: All members of class in same cluster | |
| ### References: | |
| [9] van der Maaten, L., & Hinton, G. (2008). "Visualizing Data using t-SNE." JMLR. | |
| [10] McInnes, L., et al. (2018). "UMAP: Uniform Manifold Approximation and Projection." arXiv.""" | |
| # Load notebook | |
| notebook_path = "/Users/tahamajs/Documents/uni/Sysmem2_in_AI/ComputerAssignments/CA10_knowledge_graphs/notebooks/02_Graph_Neural_Networks.ipynb" | |
| print("📖 Loading notebook...") | |
| with open(notebook_path, "r", encoding="utf-8") as f: | |
| notebook = json.load(f) | |
| print(f"✅ Loaded notebook with {len(notebook['cells'])} cells") | |
| # Process cells | |
| additions = 0 | |
| for i, cell in enumerate(notebook["cells"]): | |
| if cell["cell_type"] == "markdown": | |
| source = ( | |
| "".join(cell["source"]) | |
| if isinstance(cell["source"], list) | |
| else cell["source"] | |
| ) | |
| # Section 2 | |
| if ( | |
| "## 2. Create Knowledge Graph" in source | |
| and "2.1 Knowledge Graph Construction" not in source | |
| ): | |
| print(f"📝 Enhancing Section 2: Knowledge Graph (cell {i})...") | |
| cell["source"] = create_section2_markdown().split("\n") | |
| additions += 1 | |
| # Training section (Section 7) | |
| elif "## 7. Training GNN Models" in source or ( | |
| "### Training Function" in source and "7.1 Link Prediction" not in source | |
| ): | |
| print(f"📝 Adding comprehensive training section (cell {i})...") | |
| # Insert before existing content | |
| new_content = create_training_section_markdown() + "\n\n" + source | |
| cell["source"] = new_content.split("\n") | |
| additions += 1 | |
| # Visualization section (Section 9) | |
| elif ( | |
| "## 9. Visualization" in source | |
| and "9.1 Dimensionality Reduction" not in source | |
| ): | |
| print(f"📝 Enhancing Section 9: Visualization (cell {i})...") | |
| cell["source"] = create_visualization_section().split("\n") | |
| additions += 1 | |
| print(f"\n✅ Enhanced {additions} additional sections") | |
| # Save | |
| print("💾 Saving enhanced notebook...") | |
| with open(notebook_path, "w", encoding="utf-8") as f: | |
| json.dump(notebook, f, indent=2, ensure_ascii=False) | |
| print("✅ Notebook fully enhanced!") | |
| print(f"📍 Saved to: {notebook_path}") | |
Xet Storage Details
- Size:
- 15.5 kB
- Xet hash:
- 320e3fba0b0bb7910ff385b9b59069d7a94c49df65ca1e134117b72e4e3579cd
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.