Skip to content

Instantly share code, notes, and snippets.

@AhmedCoolProjects
Created December 25, 2025 14:01
Show Gist options
  • Select an option

  • Save AhmedCoolProjects/e6e16baadac622aaf3e27925b5c1c5ae to your computer and use it in GitHub Desktop.

Select an option

Save AhmedCoolProjects/e6e16baadac622aaf3e27925b5c1c5ae to your computer and use it in GitHub Desktop.
DGL first application.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4",
"authorship_tag": "ABX9TyO8Ord2QMQXU5LGKsCYBLyF",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU",
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"2d0e7ec76f3f4048b253a1ab4486de31": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HBoxModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_edc604e567b4449fa13d51d9a3db42d1",
"IPY_MODEL_5cf2e1fd0290418984cbb1539938174a",
"IPY_MODEL_c9e1ea31ef4a438280d31000127bd3b1"
],
"layout": "IPY_MODEL_eb21427307394065bdbeb0c50de28153"
}
},
"edc604e567b4449fa13d51d9a3db42d1": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_331e9f93bbe14010a5928eed9cf3f8f0",
"placeholder": "​",
"style": "IPY_MODEL_9e7dba44351341eebadddff103285adf",
"value": "/root/.dgl/cora_v2.zip: 100%"
}
},
"5cf2e1fd0290418984cbb1539938174a": {
"model_module": "@jupyter-widgets/controls",
"model_name": "FloatProgressModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_04e85c801b734782b9572ef2fca30000",
"max": 132173,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_147f2a7f980942a282a139d4f13eeb0b",
"value": 132173
}
},
"c9e1ea31ef4a438280d31000127bd3b1": {
"model_module": "@jupyter-widgets/controls",
"model_name": "HTMLModel",
"model_module_version": "1.5.0",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "1.5.0",
"_view_name": "HTMLView",
"description": "",
"description_tooltip": null,
"layout": "IPY_MODEL_26ccbcf552d84b81aa6ecd221a1fe6cf",
"placeholder": "​",
"style": "IPY_MODEL_5d483536e7e34160a701ea85b2b7fda3",
"value": " 132k/132k [00:00<00:00, 2.84MB/s]"
}
},
"eb21427307394065bdbeb0c50de28153": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"331e9f93bbe14010a5928eed9cf3f8f0": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"9e7dba44351341eebadddff103285adf": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
},
"04e85c801b734782b9572ef2fca30000": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"147f2a7f980942a282a139d4f13eeb0b": {
"model_module": "@jupyter-widgets/controls",
"model_name": "ProgressStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"26ccbcf552d84b81aa6ecd221a1fe6cf": {
"model_module": "@jupyter-widgets/base",
"model_name": "LayoutModel",
"model_module_version": "1.2.0",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "1.2.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"overflow_x": null,
"overflow_y": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"5d483536e7e34160a701ea85b2b7fda3": {
"model_module": "@jupyter-widgets/controls",
"model_name": "DescriptionStyleModel",
"model_module_version": "1.5.0",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "1.5.0",
"_model_name": "DescriptionStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "1.2.0",
"_view_name": "StyleView",
"description_width": ""
}
}
}
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/AhmedCoolProjects/e6e16baadac622aaf3e27925b5c1c5ae/dgl-first-application.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "FvP0-nA9kW59",
"outputId": "528790d4-07b0-4565-f72e-d0afc06888bd"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"2.4.0+cu121\n"
]
}
],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"\n",
"print(torch.__version__)"
]
},
{
"cell_type": "code",
"source": [
"# !pip uninstall -y torch torchvision torchaudio dgl -y\n",
"# !pip install torch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 --index-url https://download.pytorch.org/whl/cu121"
],
"metadata": {
"id": "giSIHlPul-4E"
},
"execution_count": 2,
"outputs": []
},
{
"cell_type": "code",
"source": [
"!pip install dgl -f https://data.dgl.ai/wheels/torch-2.4/repo.html"
],
"metadata": {
"id": "qktuSADBlN5Y"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import torch\n",
"import dgl\n",
"print(f\"Torch version: {torch.__version__}\")\n",
"print(f\"DGL version: {dgl.__version__}\")\n",
"print(f\"GPU Available: {torch.cuda.is_available()}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YseVWuJUlCfT",
"outputId": "5d60d495-fb65-4bce-f06b-5587eb23cde7"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Torch version: 2.4.0+cu121\n",
"DGL version: 2.4.0\n",
"GPU Available: True\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# Load Cora Data"
],
"metadata": {
"id": "2D_5RXNCmaop"
}
},
{
"cell_type": "code",
"source": [
"import dgl.data\n",
"\n",
"dataset = dgl.data.CoraGraphDataset()\n",
"dataset.num_classes"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 263,
"referenced_widgets": [
"2d0e7ec76f3f4048b253a1ab4486de31",
"edc604e567b4449fa13d51d9a3db42d1",
"5cf2e1fd0290418984cbb1539938174a",
"c9e1ea31ef4a438280d31000127bd3b1",
"eb21427307394065bdbeb0c50de28153",
"331e9f93bbe14010a5928eed9cf3f8f0",
"9e7dba44351341eebadddff103285adf",
"04e85c801b734782b9572ef2fca30000",
"147f2a7f980942a282a139d4f13eeb0b",
"26ccbcf552d84b81aa6ecd221a1fe6cf",
"5d483536e7e34160a701ea85b2b7fda3"
]
},
"id": "HvMOrZWElLYR",
"outputId": "2a949c08-5d23-4348-9bba-2d7977e258c4"
},
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading /root/.dgl/cora_v2.zip from https://data.dgl.ai/dataset/cora_v2.zip...\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"/root/.dgl/cora_v2.zip: 0%| | 0.00/132k [00:00<?, ?B/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "2d0e7ec76f3f4048b253a1ab4486de31"
}
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"Extracting file to /root/.dgl/cora_v2_d697a464\n",
"Finished data loading and preprocessing.\n",
" NumNodes: 2708\n",
" NumEdges: 10556\n",
" NumFeats: 1433\n",
" NumClasses: 7\n",
" NumTrainingSamples: 140\n",
" NumValidationSamples: 500\n",
" NumTestSamples: 1000\n",
"Done saving data into cached files.\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"7"
]
},
"metadata": {},
"execution_count": 6
}
]
},
{
"cell_type": "code",
"source": [
"g = dataset[0]"
],
"metadata": {
"id": "D-Cg-pA0p-Ij"
},
"execution_count": 7,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"# GCN"
],
"metadata": {
"id": "NRgh3tlpqd3z"
}
},
{
"cell_type": "code",
"source": [
"from dgl.nn import GraphConv"
],
"metadata": {
"id": "Qd8E5D8-qc9e"
},
"execution_count": 9,
"outputs": []
},
{
"cell_type": "code",
"source": [
"class GCN(nn.Module):\n",
" def __init__(self, in_feats, h_feats, num_classes):\n",
" super(GCN, self).__init__()\n",
" self.conv1 = GraphConv(in_feats, h_feats)\n",
" self.conv2 = GraphConv(h_feats, num_classes)\n",
"\n",
" def forward(self, g, in_feat):\n",
" h = self.conv1(g, in_feat)\n",
" h = F.relu(h)\n",
" h = self.conv2(g, h)\n",
" return h"
],
"metadata": {
"id": "m2aj9EIKqIe8"
},
"execution_count": 10,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model = GCN(g.ndata['feat'].shape[1], 32, dataset.num_classes)"
],
"metadata": {
"id": "JmLcdFDXrRAx"
},
"execution_count": 26,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "X6YL4CJWrsqE",
"outputId": "ab7f0443-bbca-499f-8353-60e58f7ccc2c"
},
"execution_count": 27,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"GCN(\n",
" (conv1): GraphConv(in=1433, out=32, normalization=both, activation=None)\n",
" (conv2): GraphConv(in=32, out=7, normalization=both, activation=None)\n",
")"
]
},
"metadata": {},
"execution_count": 27
}
]
},
{
"cell_type": "markdown",
"source": [
"# Training"
],
"metadata": {
"id": "jgVyXjgWr9nQ"
}
},
{
"cell_type": "code",
"source": [
"def train(g, model):\n",
" optim = torch.optim.Adam(model.parameters(), lr=0.01)\n",
" best_val_acc = 0\n",
" best_test_acc = 0\n",
"\n",
" features = g.ndata['feat']\n",
" labels = g.ndata['label']\n",
" train_mask = g.ndata['train_mask']\n",
" val_mask = g.ndata['val_mask']\n",
" test_mask = g.ndata['test_mask']\n",
"\n",
" for e in range(100):\n",
" logits = model(g, features)\n",
" pred = logits.argmax(1)\n",
"\n",
" loss = F.cross_entropy(logits[train_mask], labels[train_mask])\n",
"\n",
" train_acc = (pred[train_mask] == labels[train_mask]).float().mean()\n",
" val_acc = (pred[val_mask] == labels[val_mask]).float().mean()\n",
" test_acc = (pred[test_mask] == labels[test_mask]).float().mean()\n",
"\n",
" if best_val_acc < val_acc:\n",
" best_val_acc = val_acc\n",
" best_test_acc = test_acc\n",
"\n",
" optim.zero_grad()\n",
" loss.backward()\n",
" optim.step()\n",
"\n",
" if e % 10 == 0:\n",
" print(f\"Epoch {e} | Loss {loss.item():.4f} | Train Acc {train_acc:.4f} | Val Acc {val_acc:.4f} (Best={best_val_acc:.4f}) | Test Acc {test_acc:.4f} (Best={best_test_acc:.4f})\")\n"
],
"metadata": {
"id": "2BEOTclQrtBW"
},
"execution_count": 28,
"outputs": []
},
{
"cell_type": "code",
"source": [
"train(g, model)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "CCtwhg27t1hn",
"outputId": "c4d03e57-429e-466d-c23f-7e4de1e9baed"
},
"execution_count": 29,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Epoch 0 | Loss 1.9456 | Train Acc 0.1286 | Val Acc 0.1220 (Best=0.1220) | Test Acc 0.0990 (Best=0.0990)\n",
"Epoch 10 | Loss 1.7081 | Train Acc 0.9286 | Val Acc 0.6680 (Best=0.6680) | Test Acc 0.6700 (Best=0.6700)\n",
"Epoch 20 | Loss 1.2999 | Train Acc 0.9643 | Val Acc 0.7460 (Best=0.7460) | Test Acc 0.7420 (Best=0.7420)\n",
"Epoch 30 | Loss 0.8249 | Train Acc 0.9786 | Val Acc 0.7740 (Best=0.7740) | Test Acc 0.7680 (Best=0.7680)\n",
"Epoch 40 | Loss 0.4528 | Train Acc 0.9929 | Val Acc 0.7760 (Best=0.7800) | Test Acc 0.7850 (Best=0.7850)\n",
"Epoch 50 | Loss 0.2403 | Train Acc 0.9929 | Val Acc 0.7760 (Best=0.7800) | Test Acc 0.7900 (Best=0.7850)\n",
"Epoch 60 | Loss 0.1339 | Train Acc 1.0000 | Val Acc 0.7840 (Best=0.7880) | Test Acc 0.7910 (Best=0.7890)\n",
"Epoch 70 | Loss 0.0809 | Train Acc 1.0000 | Val Acc 0.7880 (Best=0.7880) | Test Acc 0.7910 (Best=0.7890)\n",
"Epoch 80 | Loss 0.0535 | Train Acc 1.0000 | Val Acc 0.7860 (Best=0.7900) | Test Acc 0.7860 (Best=0.7920)\n",
"Epoch 90 | Loss 0.0382 | Train Acc 1.0000 | Val Acc 0.7840 (Best=0.7900) | Test Acc 0.7810 (Best=0.7920)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"model"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "F5OO2q3ct2Xp",
"outputId": "84c53de6-3696-45f8-f015-17aad701270b"
},
"execution_count": 30,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"GCN(\n",
" (conv1): GraphConv(in=1433, out=32, normalization=both, activation=None)\n",
" (conv2): GraphConv(in=32, out=7, normalization=both, activation=None)\n",
")"
]
},
"metadata": {},
"execution_count": 30
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "5KmXkgWZuaG1"
},
"execution_count": null,
"outputs": []
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment