File size: 76,078 Bytes
354c06c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 |
{
"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
}
|