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