gcn_mp.py 2.46 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
"""GCN using basic message passing

References:
- Semi-Supervised Classification with Graph Convolutional Networks
- Paper: https://arxiv.org/abs/1609.02907
- Code: https://github.com/tkipf/gcn
"""
import mxnet as mx
from mxnet import gluon

11

12
def gcn_msg(edge):
13
14
    msg = edge.src["h"] * edge.src["norm"]
    return {"m": msg}
15
16
17


def gcn_reduce(node):
18
19
    accum = mx.nd.sum(node.mailbox["m"], 1) * node.data["norm"]
    return {"h": accum}
20
21
22
23
24
25
26


class NodeUpdate(gluon.Block):
    def __init__(self, out_feats, activation=None, bias=True):
        super(NodeUpdate, self).__init__()
        with self.name_scope():
            if bias:
27
28
29
                self.bias = self.params.get(
                    "bias", shape=(out_feats,), init=mx.init.Zero()
                )
30
31
32
33
34
            else:
                self.bias = None
        self.activation = activation

    def forward(self, node):
35
        h = node.data["h"]
36
37
38
39
        if self.bias is not None:
            h = h + self.bias.data(h.context)
        if self.activation:
            h = self.activation(h)
40
41
        return {"h": h}

42
43

class GCNLayer(gluon.Block):
44
    def __init__(self, g, in_feats, out_feats, activation, dropout, bias=True):
45
46
47
48
        super(GCNLayer, self).__init__()
        self.g = g
        self.dropout = dropout
        with self.name_scope():
49
50
51
            self.weight = self.params.get(
                "weight", shape=(in_feats, out_feats), init=mx.init.Xavier()
            )
52
53
54
55
56
57
            self.node_update = NodeUpdate(out_feats, activation, bias)

    def forward(self, h):
        if self.dropout:
            h = mx.nd.Dropout(h, p=self.dropout)
        h = mx.nd.dot(h, self.weight.data(h.context))
58
        self.g.ndata["h"] = h
59
        self.g.update_all(gcn_msg, gcn_reduce, self.node_update)
60
        h = self.g.ndata.pop("h")
61
62
63
64
        return h


class GCN(gluon.Block):
65
66
67
    def __init__(
        self, g, in_feats, n_hidden, n_classes, n_layers, activation, dropout
    ):
68
69
70
71
72
73
        super(GCN, self).__init__()
        self.layers = gluon.nn.Sequential()
        # input layer
        self.layers.add(GCNLayer(g, in_feats, n_hidden, activation, 0))
        # hidden layers
        for i in range(n_layers - 1):
74
75
76
            self.layers.add(
                GCNLayer(g, n_hidden, n_hidden, activation, dropout)
            )
77
78
79
80
81
82
83
84
        # output layer
        self.layers.add(GCNLayer(g, n_hidden, n_classes, None, dropout))

    def forward(self, features):
        h = features
        for layer in self.layers:
            h = layer(h)
        return h