forked from chaitjo/graph-convnet-tsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcn_layers.py
183 lines (149 loc) · 5.8 KB
/
gcn_layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
class BatchNormNode(nn.Module):
"""Batch normalization for node features.
"""
def __init__(self, hidden_dim):
super(BatchNormNode, self).__init__()
self.batch_norm = nn.BatchNorm1d(hidden_dim, track_running_stats=False)
def forward(self, x):
"""
Args:
x: Node features (batch_size, num_nodes, hidden_dim)
Returns:
x_bn: Node features after batch normalization (batch_size, num_nodes, hidden_dim)
"""
x_trans = x.transpose(1, 2).contiguous() # Reshape input: (batch_size, hidden_dim, num_nodes)
x_trans_bn = self.batch_norm(x_trans)
x_bn = x_trans_bn.transpose(1, 2).contiguous() # Reshape to original shape
return x_bn
class BatchNormEdge(nn.Module):
"""Batch normalization for edge features.
"""
def __init__(self, hidden_dim):
super(BatchNormEdge, self).__init__()
self.batch_norm = nn.BatchNorm2d(hidden_dim, track_running_stats=False)
def forward(self, e):
"""
Args:
e: Edge features (batch_size, num_nodes, num_nodes, hidden_dim)
Returns:
e_bn: Edge features after batch normalization (batch_size, num_nodes, num_nodes, hidden_dim)
"""
e_trans = e.transpose(1, 3).contiguous() # Reshape input: (batch_size, num_nodes, num_nodes, hidden_dim)
e_trans_bn = self.batch_norm(e_trans)
e_bn = e_trans_bn.transpose(1, 3).contiguous() # Reshape to original
return e_bn
class NodeFeatures(nn.Module):
"""Convnet features for nodes.
Using `sum` aggregation:
x_i = U*x_i + sum_j [ gate_ij * (V*x_j) ]
Using `mean` aggregation:
x_i = U*x_i + ( sum_j [ gate_ij * (V*x_j) ] / sum_j [ gate_ij] )
"""
def __init__(self, hidden_dim, aggregation="mean"):
super(NodeFeatures, self).__init__()
self.aggregation = aggregation
self.U = nn.Linear(hidden_dim, hidden_dim, True)
self.V = nn.Linear(hidden_dim, hidden_dim, True)
def forward(self, x, edge_gate):
"""
Args:
x: Node features (batch_size, num_nodes, hidden_dim)
edge_gate: Edge gate values (batch_size, num_nodes, num_nodes, hidden_dim)
Returns:
x_new: Convolved node features (batch_size, num_nodes, hidden_dim)
"""
Ux = self.U(x) # B x V x H
Vx = self.V(x) # B x V x H
Vx = Vx.unsqueeze(1) # extend Vx from "B x V x H" to "B x 1 x V x H"
gateVx = edge_gate * Vx # B x V x V x H
if self.aggregation=="mean":
x_new = Ux + torch.sum(gateVx, dim=2) / (1e-20 + torch.sum(edge_gate, dim=2)) # B x V x H
elif self.aggregation=="sum":
x_new = Ux + torch.sum(gateVx, dim=2) # B x V x H
return x_new
class EdgeFeatures(nn.Module):
"""Convnet features for edges.
e_ij = U*e_ij + V*(x_i + x_j)
"""
def __init__(self, hidden_dim):
super(EdgeFeatures, self).__init__()
self.U = nn.Linear(hidden_dim, hidden_dim, True)
self.V = nn.Linear(hidden_dim, hidden_dim, True)
def forward(self, x, e):
"""
Args:
x: Node features (batch_size, num_nodes, hidden_dim)
e: Edge features (batch_size, num_nodes, num_nodes, hidden_dim)
Returns:
e_new: Convolved edge features (batch_size, num_nodes, num_nodes, hidden_dim)
"""
Ue = self.U(e)
Vx = self.V(x)
Wx = Vx.unsqueeze(1) # Extend Vx from "B x V x H" to "B x V x 1 x H"
Vx = Vx.unsqueeze(2) # extend Vx from "B x V x H" to "B x 1 x V x H"
e_new = Ue + Vx + Wx
return e_new
class ResidualGatedGCNLayer(nn.Module):
"""Convnet layer with gating and residual connection.
"""
def __init__(self, hidden_dim, aggregation="sum"):
super(ResidualGatedGCNLayer, self).__init__()
self.node_feat = NodeFeatures(hidden_dim, aggregation)
self.edge_feat = EdgeFeatures(hidden_dim)
self.bn_node = BatchNormNode(hidden_dim)
self.bn_edge = BatchNormEdge(hidden_dim)
def forward(self, x, e):
"""
Args:
x: Node features (batch_size, num_nodes, hidden_dim)
e: Edge features (batch_size, num_nodes, num_nodes, hidden_dim)
Returns:
x_new: Convolved node features (batch_size, num_nodes, hidden_dim)
e_new: Convolved edge features (batch_size, num_nodes, num_nodes, hidden_dim)
"""
e_in = e
x_in = x
# Edge convolution
e_tmp = self.edge_feat(x_in, e_in) # B x V x V x H
# Compute edge gates
edge_gate = F.sigmoid(e_tmp)
# Node convolution
x_tmp = self.node_feat(x_in, edge_gate)
# Batch normalization
e_tmp = self.bn_edge(e_tmp)
x_tmp = self.bn_node(x_tmp)
# ReLU Activation
e = F.relu(e_tmp)
x = F.relu(x_tmp)
# Residual connection
x_new = x_in + x
e_new = e_in + e
return x_new, e_new
class MLP(nn.Module):
"""Multi-layer Perceptron for output prediction.
"""
def __init__(self, hidden_dim, output_dim, L=2):
super(MLP, self).__init__()
self.L = L
U = []
for layer in range(self.L - 1):
U.append(nn.Linear(hidden_dim, hidden_dim, True))
self.U = nn.ModuleList(U)
self.V = nn.Linear(hidden_dim, output_dim, True)
def forward(self, x):
"""
Args:
x: Input features (batch_size, hidden_dim)
Returns:
y: Output predictions (batch_size, output_dim)
"""
Ux = x
for U_i in self.U:
Ux = U_i(Ux) # B x H
Ux = F.relu(Ux) # B x H
y = self.V(Ux) # B x O
return y