link_prediction.ipynb 12.4 KB
Newer Older
1
2
3
4
{
  "cells": [
    {
      "cell_type": "markdown",
5
6
7
      "metadata": {
        "id": "Ow8CQmZIV8Yn"
      },
8
9
10
11
12
13
14
15
16
17
18
19
20
      "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"
21
      ]
22
23
24
25
26
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "onVijYWpWlMj"
27
28
29
30
      },
      "source": [
        "## Install DGL package"
      ]
31
32
33
    },
    {
      "cell_type": "code",
34
35
36
37
38
      "execution_count": null,
      "metadata": {
        "id": "QcpjTazg6hEo"
      },
      "outputs": [],
39
40
41
42
43
44
45
      "source": [
        "# Install required packages.\n",
        "import os\n",
        "import torch\n",
        "os.environ['TORCH'] = torch.__version__\n",
        "os.environ['DGLBACKEND'] = \"pytorch\"\n",
        "\n",
46
        "# Install the CUDA version. If you want to install CPU version, please\n",
47
        "# refer to https://www.dgl.ai/pages/start.html.\n",
48
49
        "device = torch.device(\"cuda\")\n",
        "!pip install --pre dgl -f https://data.dgl.ai/wheels-test/cu121/repo.html\n",
50
51
52
53
54
55
56
57
58
        "\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!\")"
59
      ]
60
61
62
    },
    {
      "cell_type": "markdown",
63
64
65
      "metadata": {
        "id": "OOKZxxT7W1Rz"
      },
66
67
68
      "source": [
        "## Loading Dataset\n",
        "`cora` is already prepared as `BuiltinDataset` in **GraphBolt**.\n"
69
      ]
70
71
72
    },
    {
      "cell_type": "code",
73
      "execution_count": null,
74
75
76
      "metadata": {
        "id": "RnJkkSKhWiUG"
      },
77
78
79
80
      "outputs": [],
      "source": [
        "dataset = gb.BuiltinDataset(\"cora\").load()"
      ]
81
82
83
84
85
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WxnTMEQXXKsM"
86
87
88
89
      },
      "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."
      ]
90
91
92
    },
    {
      "cell_type": "code",
93
94
95
96
97
      "execution_count": null,
      "metadata": {
        "id": "YCm8CGkOX9lK"
      },
      "outputs": [],
98
      "source": [
99
100
        "graph = dataset.graph.to(device)\n",
        "feature = dataset.feature.to(device)\n",
101
102
103
104
        "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}.\")"
105
      ]
106
107
108
    },
    {
      "cell_type": "markdown",
109
110
111
      "metadata": {
        "id": "2y-P5omQYP00"
      },
112
113
114
115
116
117
118
119
      "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"
120
      ]
121
122
123
    },
    {
      "cell_type": "code",
124
      "execution_count": null,
125
126
127
      "metadata": {
        "id": "LZgXGfBvYijJ"
      },
128
129
130
131
132
133
134
135
136
137
138
139
      "outputs": [],
      "source": [
        "from functools import partial\n",
        "def create_train_dataloader():\n",
        "    datapipe = gb.ItemSampler(train_set, batch_size=256, shuffle=True)\n",
        "    datapipe = datapipe.copy_to(device)\n",
        "    datapipe = datapipe.sample_uniform_negative(graph, 5)\n",
        "    datapipe = datapipe.sample_neighbor(graph, [5, 5])\n",
        "    datapipe = datapipe.transform(partial(gb.exclude_seed_edges, include_reverse_edges=True))\n",
        "    datapipe = datapipe.fetch_feature(feature, node_feature_keys=[\"feat\"])\n",
        "    return gb.DataLoader(datapipe)"
      ]
140
141
142
    },
    {
      "cell_type": "markdown",
143
144
145
      "metadata": {
        "id": "5sU_aulqYkwK"
      },
146
147
148
      "source": [
        "You can peek one minibatch from train_dataloader and see what it will give you.\n",
        "\n"
149
      ]
150
151
152
    },
    {
      "cell_type": "code",
153
      "execution_count": null,
154
155
156
      "metadata": {
        "id": "euEdzmerYmZi"
      },
157
158
159
160
161
      "outputs": [],
      "source": [
        "data = next(iter(create_train_dataloader()))\n",
        "print(f\"MiniBatch: {data}\")"
      ]
162
163
164
    },
    {
      "cell_type": "markdown",
165
166
167
      "metadata": {
        "id": "WYQqfrDWYtU0"
      },
168
169
170
      "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"
171
      ]
172
173
174
    },
    {
      "cell_type": "code",
175
176
177
178
179
      "execution_count": null,
      "metadata": {
        "id": "0qQbBwO7Y3-Q"
      },
      "outputs": [],
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
      "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"
207
      ]
208
209
210
    },
    {
      "cell_type": "markdown",
211
212
213
      "metadata": {
        "id": "y23JppwHY5MC"
      },
214
215
216
217
      "source": [
        "## Defining Traing Loop\n",
        "The following initializes the model and defines the optimizer.\n",
        "\n"
218
      ]
219
220
221
    },
    {
      "cell_type": "code",
222
223
224
225
226
      "execution_count": null,
      "metadata": {
        "id": "omSIB_ePZACg"
      },
      "outputs": [],
227
228
229
230
      "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)"
231
      ]
232
233
234
    },
    {
      "cell_type": "markdown",
235
236
237
      "metadata": {
        "id": "QyWtzNZcZRgp"
      },
238
239
240
      "source": [
        "The following is the training loop for link prediction and evaluation.\n",
        "\n"
241
      ]
242
243
244
    },
    {
      "cell_type": "code",
245
246
247
248
249
      "execution_count": null,
      "metadata": {
        "id": "SccLVrjSZSkd"
      },
      "outputs": [],
250
251
252
253
254
      "source": [
        "import tqdm\n",
        "for epoch in range(3):\n",
        "    model.train()\n",
        "    total_loss = 0\n",
255
        "    for step, data in tqdm.tqdm(enumerate(create_train_dataloader())):\n",
Rhett Ying's avatar
Rhett Ying committed
256
257
        "        # Get node pairs with labels for loss calculation.\n",
        "        compacted_pairs, labels = data.node_pairs_with_labels\n",
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        "        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}\")"
277
      ]
278
279
280
281
282
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pxow2XSkZXoO"
283
284
285
286
      },
      "source": [
        "## Evaluating Performance with Link Prediction\n"
      ]
287
288
289
    },
    {
      "cell_type": "code",
290
291
292
293
294
      "execution_count": null,
      "metadata": {
        "id": "IMulfsnIZZVh"
      },
      "outputs": [],
295
296
297
298
      "source": [
        "model.eval()\n",
        "\n",
        "datapipe = gb.ItemSampler(test_set, batch_size=256, shuffle=False)\n",
299
        "datapipe = datapipe.copy_to(device)\n",
300
301
302
303
        "# 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",
304
        "eval_dataloader = gb.DataLoader(datapipe, num_workers=0)\n",
305
306
307
        "\n",
        "logits = []\n",
        "labels = []\n",
308
        "for step, data in tqdm.tqdm(enumerate(eval_dataloader)):\n",
Rhett Ying's avatar
Rhett Ying committed
309
310
        "    # Get node pairs with labels for loss calculation.\n",
        "    compacted_pairs, label = data.node_pairs_with_labels\n",
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
        "\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",
333
        "auc = roc_auc_score(labels.cpu(), logits.cpu())\n",
334
        "print(\"Link Prediction AUC:\", auc)"
335
      ]
336
337
338
    },
    {
      "cell_type": "markdown",
339
340
341
      "metadata": {
        "id": "KoCoIvqAZeCS"
      },
342
343
344
      "source": [
        "## Conclusion\n",
        "In this tutorial, you have learned how to train a multi-layer GraphSAGE for link prediction with neighbor sampling."
345
346
347
348
349
350
      ]
    }
  ],
  "metadata": {
    "colab": {
      "private_outputs": true,
351
352
      "provenance": [],
      "gpuType": "T4"
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.10.12"
369
370
    },
    "accelerator": "GPU"
371
372
373
  },
  "nbformat": 4,
  "nbformat_minor": 0
374
}