link_prediction.ipynb 11.8 KB
Newer Older
1
2
3
4
5
6
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "private_outputs": true,
7
      "provenance": []
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
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Link Prediction\n",
        "\n",
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb) [![GitHub](https://img.shields.io/badge/-View%20on%20GitHub-181717?logo=github&logoColor=ffffff)](https://github.com/dmlc/dgl/blob/master/notebooks/stochastic_training/link_prediction.ipynb)\n",
        "\n",
        "This tutorial will show how to train a multi-layer GraphSAGE for link\n",
        "prediction on [CoraGraphDataset](https://data.dgl.ai/dataset/cora_v2.zip).\n",
        "The dataset contains 2708 nodes and 10556 edges.\n",
        "\n",
        "By the end of this tutorial, you will be able to\n",
        "\n",
        "-  Train a GNN model for link prediction on target device with DGL's\n",
        "   neighbor sampling components.\n"
      ],
      "metadata": {
        "id": "Ow8CQmZIV8Yn"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Install DGL package"
      ],
      "metadata": {
        "id": "onVijYWpWlMj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Install required packages.\n",
        "import os\n",
        "import torch\n",
        "import numpy as np\n",
        "os.environ['TORCH'] = torch.__version__\n",
        "os.environ['DGLBACKEND'] = \"pytorch\"\n",
        "\n",
        "# Install the CPU version.\n",
        "device = torch.device(\"cpu\")\n",
        "!pip install --pre dgl -f https://data.dgl.ai/wheels-test/repo.html\n",
        "\n",
        "try:\n",
        "    import dgl\n",
        "    import dgl.graphbolt as gb\n",
        "    installed = True\n",
        "except ImportError as error:\n",
        "    installed = False\n",
        "    print(error)\n",
        "print(\"DGL installed!\" if installed else \"DGL not found!\")"
      ],
      "metadata": {
        "id": "QcpjTazg6hEo"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Loading Dataset\n",
        "`cora` is already prepared as `BuiltinDataset` in **GraphBolt**.\n"
      ],
      "metadata": {
        "id": "OOKZxxT7W1Rz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "dataset = gb.BuiltinDataset(\"cora\").load()"
      ],
      "metadata": {
        "id": "RnJkkSKhWiUG"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Dataset consists of graph, feature and tasks. You can get the training-validation-test set from the tasks. Seed nodes and corresponding labels are already stored in each training-validation-test set. This dataset contains 2 tasks, one for node classification and the other for link prediction. We will use the link prediction task."
      ],
      "metadata": {
        "id": "WxnTMEQXXKsM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "graph = dataset.graph\n",
        "feature = dataset.feature\n",
        "train_set = dataset.tasks[1].train_set\n",
        "test_set = dataset.tasks[1].test_set\n",
        "task_name = dataset.tasks[1].metadata[\"name\"]\n",
        "print(f\"Task: {task_name}.\")"
      ],
      "metadata": {
        "id": "YCm8CGkOX9lK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Defining Neighbor Sampler and Data Loader in DGL\n",
        "Different from the link prediction tutorial for full graph, a common practice to train GNN on large graphs is to iterate over the edges in minibatches, since computing the probability of all edges is usually impossible. For each minibatch of edges, you compute the output representation of their incident nodes using neighbor sampling and GNN, in a similar fashion introduced in the node classification tutorial.\n",
        "\n",
        "To perform link prediction, you need to specify a negative sampler. DGL provides builtin negative samplers such as `dgl.graphbolt.UniformNegativeSampler`. Here this tutorial uniformly draws 5 negative examples per positive example.\n",
        "\n",
        "Except for the negative sampler, the rest of the code is identical to the node classification tutorial.\n",
        "\n"
      ],
      "metadata": {
        "id": "2y-P5omQYP00"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "datapipe = gb.ItemSampler(train_set, batch_size=256, shuffle=True)\n",
        "datapipe = datapipe.sample_uniform_negative(graph, 5)\n",
        "datapipe = datapipe.sample_neighbor(graph, [5, 5, 5])\n",
        "datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
        "datapipe = datapipe.copy_to(device)\n",
145
        "train_dataloader = gb.DataLoader(datapipe, num_workers=0)"
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
      ],
      "metadata": {
        "id": "LZgXGfBvYijJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "You can peek one minibatch from train_dataloader and see what it will give you.\n",
        "\n"
      ],
      "metadata": {
        "id": "5sU_aulqYkwK"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "data = next(iter(train_dataloader))\n",
167
        "print(f\"MiniBatch: {data}\")"
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
      ],
      "metadata": {
        "id": "euEdzmerYmZi"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Defining Model for Node Representation\n",
        "Let’s consider training a 2-layer GraphSAGE with neighbor sampling. The model can be written as follows:\n"
      ],
      "metadata": {
        "id": "WYQqfrDWYtU0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import dgl.nn as dglnn\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "\n",
        "\n",
        "class SAGE(nn.Module):\n",
        "    def __init__(self, in_size, hidden_size):\n",
        "        super().__init__()\n",
        "        self.layers = nn.ModuleList()\n",
        "        self.layers.append(dglnn.SAGEConv(in_size, hidden_size, \"mean\"))\n",
        "        self.layers.append(dglnn.SAGEConv(hidden_size, hidden_size, \"mean\"))\n",
        "        self.hidden_size = hidden_size\n",
        "        self.predictor = nn.Sequential(\n",
        "            nn.Linear(hidden_size, hidden_size),\n",
        "            nn.ReLU(),\n",
        "            nn.Linear(hidden_size, 1),\n",
        "        )\n",
        "\n",
        "    def forward(self, blocks, x):\n",
        "        hidden_x = x\n",
        "        for layer_idx, (layer, block) in enumerate(zip(self.layers, blocks)):\n",
        "            hidden_x = layer(block, hidden_x)\n",
        "            is_last_layer = layer_idx == len(self.layers) - 1\n",
        "            if not is_last_layer:\n",
        "                hidden_x = F.relu(hidden_x)\n",
        "        return hidden_x"
      ],
      "metadata": {
        "id": "0qQbBwO7Y3-Q"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Defining Traing Loop\n",
        "The following initializes the model and defines the optimizer.\n",
        "\n"
      ],
      "metadata": {
        "id": "y23JppwHY5MC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "in_size = feature.size(\"node\", None, \"feat\")[0]\n",
        "model = SAGE(in_size, 128).to(device)\n",
        "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)"
      ],
      "metadata": {
        "id": "omSIB_ePZACg"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "The following is the training loop for link prediction and evaluation.\n",
        "\n"
      ],
      "metadata": {
        "id": "QyWtzNZcZRgp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import tqdm\n",
        "for epoch in range(3):\n",
        "    model.train()\n",
        "    total_loss = 0\n",
        "    for step, data in tqdm.tqdm(enumerate(train_dataloader)):\n",
Rhett Ying's avatar
Rhett Ying committed
263
264
        "        # Get node pairs with labels for loss calculation.\n",
        "        compacted_pairs, labels = data.node_pairs_with_labels\n",
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
        "        node_feature = data.node_features[\"feat\"]\n",
        "        # Convert sampled subgraphs to DGL blocks.\n",
        "        blocks = data.blocks\n",
        "\n",
        "        # Get the embeddings of the input nodes.\n",
        "        y = model(blocks, node_feature)\n",
        "        logits = model.predictor(\n",
        "            y[compacted_pairs[0]] * y[compacted_pairs[1]]\n",
        "        ).squeeze()\n",
        "\n",
        "        # Compute loss.\n",
        "        loss = F.binary_cross_entropy_with_logits(logits, labels)\n",
        "        optimizer.zero_grad()\n",
        "        loss.backward()\n",
        "        optimizer.step()\n",
        "\n",
        "        total_loss += loss.item()\n",
        "\n",
        "    print(f\"Epoch {epoch:03d} | Loss {total_loss / (step + 1):.3f}\")"
      ],
      "metadata": {
        "id": "SccLVrjSZSkd"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Evaluating Performance with Link Prediction\n"
      ],
      "metadata": {
        "id": "pxow2XSkZXoO"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "model.eval()\n",
        "\n",
        "datapipe = gb.ItemSampler(test_set, batch_size=256, shuffle=False)\n",
        "# Since we need to use all neghborhoods for evaluation, we set the fanout\n",
        "# to -1.\n",
        "datapipe = datapipe.sample_neighbor(graph, [-1, -1])\n",
        "datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
        "datapipe = datapipe.copy_to(device)\n",
311
        "eval_dataloader = gb.DataLoader(datapipe, num_workers=0)\n",
312
313
314
315
        "\n",
        "logits = []\n",
        "labels = []\n",
        "for step, data in enumerate(eval_dataloader):\n",
Rhett Ying's avatar
Rhett Ying committed
316
317
        "    # Get node pairs with labels for loss calculation.\n",
        "    compacted_pairs, label = data.node_pairs_with_labels\n",
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
        "\n",
        "    # The features of sampled nodes.\n",
        "    x = data.node_features[\"feat\"]\n",
        "\n",
        "    # Forward.\n",
        "    y = model(data.blocks, x)\n",
        "    logit = (\n",
        "        model.predictor(y[compacted_pairs[0]] * y[compacted_pairs[1]])\n",
        "        .squeeze()\n",
        "        .detach()\n",
        "    )\n",
        "\n",
        "    logits.append(logit)\n",
        "    labels.append(label)\n",
        "\n",
        "logits = torch.cat(logits, dim=0)\n",
        "labels = torch.cat(labels, dim=0)\n",
        "\n",
        "\n",
        "# Compute the AUROC score.\n",
        "from sklearn.metrics import roc_auc_score\n",
        "\n",
        "auc = roc_auc_score(labels, logits)\n",
        "print(\"Link Prediction AUC:\", auc)"
      ],
      "metadata": {
        "id": "IMulfsnIZZVh"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Conclusion\n",
        "In this tutorial, you have learned how to train a multi-layer GraphSAGE for link prediction with neighbor sampling."
      ],
      "metadata": {
        "id": "KoCoIvqAZeCS"
      }
    }
  ]
360
}