gcn.py 3.12 KB
Newer Older
paoxiaode's avatar
paoxiaode committed
1
2
3
4
5
"""
[Semi-Supervised Classification with Graph Convolutional Networks]
(https://arxiv.org/abs/1609.02907)
"""

6
import dgl.sparse as dglsp
paoxiaode's avatar
paoxiaode committed
7
8
9
10
11
12
13
14
15
16
17
18
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.data import CoraGraphDataset
from torch.optim import Adam


class GCN(nn.Module):
    def __init__(self, in_size, out_size, hidden_size=16):
        super().__init__()

        # Two-layer GCN.
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
19
20
        self.W1 = nn.Linear(in_size, hidden_size)
        self.W2 = nn.Linear(hidden_size, out_size)
paoxiaode's avatar
paoxiaode committed
21
22

    ############################################################################
23
24
    # (HIGHLIGHT) Take the advantage of DGL sparse APIs to implement the GCN
    # forward process.
paoxiaode's avatar
paoxiaode committed
25
26
    ############################################################################
    def forward(self, A_norm, X):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
27
        X = A_norm @ self.W1(X)
paoxiaode's avatar
paoxiaode committed
28
        X = F.relu(X)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
29
        X = A_norm @ self.W2(X)
paoxiaode's avatar
paoxiaode committed
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
        return X


def evaluate(g, pred):
    label = g.ndata["label"]
    val_mask = g.ndata["val_mask"]
    test_mask = g.ndata["test_mask"]

    # Compute accuracy on validation/test set.
    val_acc = (pred[val_mask] == label[val_mask]).float().mean()
    test_acc = (pred[test_mask] == label[test_mask]).float().mean()
    return val_acc, test_acc


def train(model, g, A_norm, X):
    label = g.ndata["label"]
    train_mask = g.ndata["train_mask"]
    optimizer = Adam(model.parameters(), lr=1e-2, weight_decay=5e-4)
    loss_fcn = nn.CrossEntropyLoss()

    for epoch in range(200):
        model.train()

        # Forward.
        logits = model(A_norm, X)

        # Compute loss with nodes in the training set.
        loss = loss_fcn(logits[train_mask], label[train_mask])

        # Backward.
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # Compute prediction.
        pred = logits.argmax(dim=1)

        # Evaluate the prediction.
        val_acc, test_acc = evaluate(g, pred)
        if epoch % 20 == 0:
            print(
                f"In epoch {epoch}, loss: {loss:.3f}, val acc: {val_acc:.3f}"
                f", test acc: {test_acc:.3f}"
            )


if __name__ == "__main__":
    # If CUDA is available, use GPU to accelerate the training, use CPU
    # otherwise.
    dev = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

    # Load graph from the existing dataset.
    dataset = CoraGraphDataset()
    g = dataset[0].to(dev)
    num_classes = dataset.num_classes
    X = g.ndata["feat"]

    # Create the adjacency matrix of graph.
    src, dst = g.edges()
    N = g.num_nodes()
90
    A = dglsp.create_from_coo(dst, src, shape=(N, N))
paoxiaode's avatar
paoxiaode committed
91
92

    ############################################################################
93
94
    # (HIGHLIGHT) Compute the symmetrically normalized adjacency matrix with
    # Sparse Matrix API
paoxiaode's avatar
paoxiaode committed
95
    ############################################################################
96
    I = dglsp.identity(A.shape, device=dev)
paoxiaode's avatar
paoxiaode committed
97
    A_hat = A + I
98
    D_hat = dglsp.diag(A_hat.sum(1)) ** -0.5
paoxiaode's avatar
paoxiaode committed
99
100
101
102
103
104
105
106
107
    A_norm = D_hat @ A_hat @ D_hat

    # Create model.
    in_size = X.shape[1]
    out_size = num_classes
    model = GCN(in_size, out_size).to(dev)

    # Kick off training.
    train(model, g, A_norm, X)