gin.py 5.67 KB
Newer Older
kitaev-chen's avatar
kitaev-chen committed
1
2
3
4
5
6
7
8
9
10
11
"""
How Powerful are Graph Neural Networks
https://arxiv.org/abs/1810.00826
https://openreview.net/forum?id=ryGs6iA5Km
Author's implementation: https://github.com/weihua916/powerful-gnns
"""


import torch
import torch.nn as nn
import torch.nn.functional as F
12
from dgl.nn.pytorch.conv import GINConv
13
from dgl.nn.pytorch.glob import SumPooling, AvgPooling, MaxPooling
kitaev-chen's avatar
kitaev-chen committed
14
15


16
class ApplyNodeFunc(nn.Module):
kitaev-chen's avatar
kitaev-chen committed
17
    """Update the node feature hv with MLP, BN and ReLU."""
18
19
    def __init__(self, mlp):
        super(ApplyNodeFunc, self).__init__()
kitaev-chen's avatar
kitaev-chen committed
20
21
22
        self.mlp = mlp
        self.bn = nn.BatchNorm1d(self.mlp.output_dim)

23
24
    def forward(self, h):
        h = self.mlp(h)
kitaev-chen's avatar
kitaev-chen committed
25
26
        h = self.bn(h)
        h = F.relu(h)
27
        return h
kitaev-chen's avatar
kitaev-chen committed
28
29
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


class MLP(nn.Module):
    """MLP with linear output"""
    def __init__(self, num_layers, input_dim, hidden_dim, output_dim):
        """MLP layers construction

        Paramters
        ---------
        num_layers: int
            The number of linear layers
        input_dim: int
            The dimensionality of input features
        hidden_dim: int
            The dimensionality of hidden units at ALL layers
        output_dim: int
            The number of classes for prediction

        """
        super(MLP, self).__init__()
        self.linear_or_not = True  # default is linear model
        self.num_layers = num_layers
        self.output_dim = output_dim

        if num_layers < 1:
            raise ValueError("number of layers should be positive!")
        elif num_layers == 1:
            # Linear model
            self.linear = nn.Linear(input_dim, output_dim)
        else:
            # Multi-layer model
            self.linear_or_not = False
            self.linears = torch.nn.ModuleList()
            self.batch_norms = torch.nn.ModuleList()

63
            self.linears.append(nn.Linear(input_dim, hidden_dim, bias=False))
kitaev-chen's avatar
kitaev-chen committed
64
            for layer in range(num_layers - 2):
65
66
                self.linears.append(nn.Linear(hidden_dim, hidden_dim, bias=False))
            self.linears.append(nn.Linear(hidden_dim, output_dim, bias=False))
kitaev-chen's avatar
kitaev-chen committed
67
68
69
70
71
72
73
74
75
76
77

            for layer in range(num_layers - 1):
                self.batch_norms.append(nn.BatchNorm1d((hidden_dim)))

    def forward(self, x):
        if self.linear_or_not:
            # If linear model
            return self.linear(x)
        else:
            # If MLP
            h = x
78
79
80
            for i in range(self.num_layers - 1):
                h = F.relu(self.batch_norms[i](self.linears[i](h)))
            return self.linears[-1](h)
kitaev-chen's avatar
kitaev-chen committed
81
82
83
84
85
86


class GIN(nn.Module):
    """GIN model"""
    def __init__(self, num_layers, num_mlp_layers, input_dim, hidden_dim,
                 output_dim, final_dropout, learn_eps, graph_pooling_type,
87
                 neighbor_pooling_type):
kitaev-chen's avatar
kitaev-chen committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        """model parameters setting

        Paramters
        ---------
        num_layers: int
            The number of linear layers in the neural network
        num_mlp_layers: int
            The number of linear layers in mlps
        input_dim: int
            The dimensionality of input features
        hidden_dim: int
            The dimensionality of hidden units at ALL layers
        output_dim: int
            The number of classes for prediction
        final_dropout: float
            dropout ratio on the final linear layer
        learn_eps: boolean
            If True, learn epsilon to distinguish center nodes from neighbors
            If False, aggregate neighbors and center nodes altogether.
        neighbor_pooling_type: str
            how to aggregate neighbors (sum, mean, or max)
        graph_pooling_type: str
            how to aggregate entire nodes in a graph (sum, mean or max)

        """
        super(GIN, self).__init__()
        self.num_layers = num_layers
        self.learn_eps = learn_eps

        # List of MLPs
        self.ginlayers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()

        for layer in range(self.num_layers - 1):
            if layer == 0:
                mlp = MLP(num_mlp_layers, input_dim, hidden_dim, hidden_dim)
            else:
                mlp = MLP(num_mlp_layers, hidden_dim, hidden_dim, hidden_dim)

127
128
            self.ginlayers.append(
                GINConv(ApplyNodeFunc(mlp), neighbor_pooling_type, 0, self.learn_eps))
kitaev-chen's avatar
kitaev-chen committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
            self.batch_norms.append(nn.BatchNorm1d(hidden_dim))

        # Linear function for graph poolings of output of each layer
        # which maps the output of different layers into a prediction score
        self.linears_prediction = torch.nn.ModuleList()

        for layer in range(num_layers):
            if layer == 0:
                self.linears_prediction.append(
                    nn.Linear(input_dim, output_dim))
            else:
                self.linears_prediction.append(
                    nn.Linear(hidden_dim, output_dim))

143
144
145
146
147
148
149
150
151
152
        self.drop = nn.Dropout(final_dropout)

        if graph_pooling_type == 'sum':
            self.pool = SumPooling()
        elif graph_pooling_type == 'mean':
            self.pool = AvgPooling()
        elif graph_pooling_type == 'max':
            self.pool = MaxPooling()
        else:
            raise NotImplementedError
kitaev-chen's avatar
kitaev-chen committed
153

154
    def forward(self, g, h):
kitaev-chen's avatar
kitaev-chen committed
155
156
157
        # list of hidden representation at each layer (including input)
        hidden_rep = [h]

158
159
160
        for i in range(self.num_layers - 1):
            h = self.ginlayers[i](g, h)
            h = self.batch_norms[i](h)
VoVAllen's avatar
VoVAllen committed
161
            h = F.relu(h)
kitaev-chen's avatar
kitaev-chen committed
162
163
164
165
166
            hidden_rep.append(h)

        score_over_layer = 0

        # perform pooling over all nodes in each graph in every layer
167
168
169
        for i, h in enumerate(hidden_rep):
            pooled_h = self.pool(g, h)
            score_over_layer += self.drop(self.linears_prediction[i](pooled_h))
kitaev-chen's avatar
kitaev-chen committed
170
171

        return score_over_layer