gcn_spmv.py 5.74 KB
Newer Older
Minjie Wang's avatar
Minjie Wang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
Semi-Supervised Classification with Graph Convolutional Networks
Paper: https://arxiv.org/abs/1609.02907
Code: https://github.com/tkipf/gcn

GCN with SPMV specialization.
"""
import argparse
import numpy as np
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
14
import dgl.function as fn
Minjie Wang's avatar
Minjie Wang committed
15
from dgl import DGLGraph
16
from dgl.data import register_data_args, load_data
Minjie Wang's avatar
Minjie Wang committed
17

18
class NodeApplyModule(nn.Module):
Minjie Wang's avatar
Minjie Wang committed
19
    def __init__(self, in_feats, out_feats, activation=None):
20
        super(NodeApplyModule, self).__init__()
Minjie Wang's avatar
Minjie Wang committed
21
        self.linear = nn.Linear(in_feats, out_feats)
22
        nn.init.xavier_normal_(self.linear.weight)
Minjie Wang's avatar
Minjie Wang committed
23
24
        self.activation = activation

25
    def forward(self, nodes):
26
27
28
        # normalization by square root of dst degree
        h = nodes.data['h'] * nodes.data['norm']
        h = self.linear(h)
Minjie Wang's avatar
Minjie Wang committed
29
30
        if self.activation:
            h = self.activation(h)
Mufei Li's avatar
Mufei Li committed
31
        return {'h': h}
Minjie Wang's avatar
Minjie Wang committed
32
33
34
35
36
37
38
39
40
41
42
43

class GCN(nn.Module):
    def __init__(self,
                 g,
                 in_feats,
                 n_hidden,
                 n_classes,
                 n_layers,
                 activation,
                 dropout):
        super(GCN, self).__init__()
        self.g = g
Mufei Li's avatar
Mufei Li committed
44
45
46
47
48
49

        if dropout:
            self.dropout = nn.Dropout(p=dropout)
        else:
            self.dropout = 0.

50
51
        self.layers = nn.ModuleList()

Minjie Wang's avatar
Minjie Wang committed
52
        # input layer
53
        self.layers.append(NodeApplyModule(in_feats, n_hidden, activation))
Mufei Li's avatar
Mufei Li committed
54

Minjie Wang's avatar
Minjie Wang committed
55
56
        # hidden layers
        for i in range(n_layers - 1):
57
            self.layers.append(NodeApplyModule(n_hidden, n_hidden, activation))
Mufei Li's avatar
Mufei Li committed
58

Minjie Wang's avatar
Minjie Wang committed
59
        # output layer
60
        self.layers.append(NodeApplyModule(n_hidden, n_classes))
Minjie Wang's avatar
Minjie Wang committed
61
62

    def forward(self, features):
63
        self.g.ndata['h'] = features
Mufei Li's avatar
Mufei Li committed
64

65
        for idx, layer in enumerate(self.layers):
Minjie Wang's avatar
Minjie Wang committed
66
            # apply dropout
67
68
69
70
            if idx > 0 and self.dropout:
                self.g.ndata['h'] = self.dropout(self.g.ndata['h'])
            # normalization by square root of src degree
            self.g.ndata['h'] = self.g.ndata['h'] * self.g.ndata['norm']
Minjie Wang's avatar
Minjie Wang committed
71
            self.g.update_all(fn.copy_src(src='h', out='m'),
Minjie Wang's avatar
Minjie Wang committed
72
                              fn.sum(msg='m', out='h'),
Minjie Wang's avatar
Minjie Wang committed
73
74
                              layer)
        return self.g.pop_n_repr('h')
Minjie Wang's avatar
Minjie Wang committed
75

76
77
78
79
80
81
82
83
84
85
def evaluate(model, features, labels, mask):
    model.eval()
    with torch.no_grad():
        logits = model(features)
        logits = logits[mask]
        labels = labels[mask]
        _, indices = torch.max(logits, dim=1)
        correct = torch.sum(indices == labels)
        return correct.item() * 1.0 / len(labels)

Minjie Wang's avatar
Minjie Wang committed
86
87
def main(args):
    # load and preprocess dataset
88
    data = load_data(args)
Minjie Wang's avatar
Minjie Wang committed
89
90
    features = torch.FloatTensor(data.features)
    labels = torch.LongTensor(data.labels)
91
92
93
    train_mask = torch.ByteTensor(data.train_mask)
    val_mask = torch.ByteTensor(data.val_mask)
    test_mask = torch.ByteTensor(data.test_mask)
Minjie Wang's avatar
Minjie Wang committed
94
95
96
97
98
99
100
101
102
103
104
    in_feats = features.shape[1]
    n_classes = data.num_labels
    n_edges = data.graph.number_of_edges()

    if args.gpu < 0:
        cuda = False
    else:
        cuda = True
        torch.cuda.set_device(args.gpu)
        features = features.cuda()
        labels = labels.cuda()
105
106
107
        train_mask = train_mask.cuda()
        val_mask = val_mask.cuda()
        test_mask = test_mask.cuda()
Minjie Wang's avatar
Minjie Wang committed
108

109
    # graph preprocess and calculate normalization factor
Minjie Wang's avatar
Minjie Wang committed
110
    g = DGLGraph(data.graph)
111
112
113
114
115
116
117
118
119
120
121
122
    n_edges = g.number_of_edges()
    # add self loop
    g.add_edges(g.nodes(), g.nodes())
    # normalization
    degs = g.in_degrees().float()
    norm = torch.pow(degs, -0.5)
    norm[torch.isinf(norm)] = 0
    if cuda:
        norm = norm.cuda()
    g.ndata['norm'] = norm.unsqueeze(1)

    # create GCN model
Minjie Wang's avatar
Minjie Wang committed
123
124
125
126
127
128
129
130
131
132
133
134
    model = GCN(g,
                in_feats,
                args.n_hidden,
                n_classes,
                args.n_layers,
                F.relu,
                args.dropout)

    if cuda:
        model.cuda()

    # use optimizer
135
136
137
    optimizer = torch.optim.Adam(model.parameters(),
                                 lr=args.lr,
                                 weight_decay=args.weight_decay)
Minjie Wang's avatar
Minjie Wang committed
138
139
140
141

    # initialize graph
    dur = []
    for epoch in range(args.n_epochs):
142
        model.train()
Minjie Wang's avatar
Minjie Wang committed
143
144
145
146
147
        if epoch >= 3:
            t0 = time.time()
        # forward
        logits = model(features)
        logp = F.log_softmax(logits, 1)
148
        loss = F.nll_loss(logp[train_mask], labels[train_mask])
Minjie Wang's avatar
Minjie Wang committed
149
150
151
152
153
154
155
156

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

        if epoch >= 3:
            dur.append(time.time() - t0)

157
158
159
160
161
162
163
164
165
        acc = evaluate(model, features, labels, val_mask)
        print("Epoch {:05d} | Time(s) {:.4f} | Loss {:.4f} | Accuracy {:.4f} | "
              "ETputs(KTEPS) {:.2f}". format(epoch, np.mean(dur), loss.item(),
                                             acc, n_edges / np.mean(dur) / 1000))

    print()
    acc = evaluate(model, features, labels, test_mask)
    print("Test Accuracy {:.4f}".format(acc))

Minjie Wang's avatar
Minjie Wang committed
166
167
168

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='GCN')
169
    register_data_args(parser)
170
    parser.add_argument("--dropout", type=float, default=0.5,
Minjie Wang's avatar
Minjie Wang committed
171
172
173
            help="dropout probability")
    parser.add_argument("--gpu", type=int, default=-1,
            help="gpu")
174
    parser.add_argument("--lr", type=float, default=1e-2,
Minjie Wang's avatar
Minjie Wang committed
175
            help="learning rate")
176
    parser.add_argument("--n-epochs", type=int, default=200,
Minjie Wang's avatar
Minjie Wang committed
177
178
179
180
181
            help="number of training epochs")
    parser.add_argument("--n-hidden", type=int, default=16,
            help="number of hidden gcn units")
    parser.add_argument("--n-layers", type=int, default=1,
            help="number of hidden gcn layers")
182
183
    parser.add_argument("--weight-decay", type=float, default=5e-4,
            help="Weight for L2 loss")
Minjie Wang's avatar
Minjie Wang committed
184
185
186
187
    args = parser.parse_args()
    print(args)

    main(args)