-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_ns.py
431 lines (315 loc) · 16.4 KB
/
model_ns.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree, softmax
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool, GlobalAttention, Set2Set
import torch.nn.functional as F
from loader import BioDataset
from dataloader import DataLoaderFinetune
from torch_scatter import scatter_add
from torch_geometric.nn.inits import glorot, zeros
class GINConv(MessagePassing):
"""
Extension of GIN aggregation to incorporate edge information by concatenation.
Args:
emb_dim (int): dimensionality of embeddings for nodes and edges.
input_layer (bool): whethe the GIN conv is applied to input layer or not. (Input node labels are uniform...)
See https://arxiv.org/abs/1810.00826
"""
def __init__(self, emb_dim, aggr = "add", input_layer = False):
super(GINConv, self).__init__()
# multi-layer perceptron
self.mlp = torch.nn.Sequential(torch.nn.Linear(2*emb_dim, 2*emb_dim), torch.nn.BatchNorm1d(2*emb_dim), torch.nn.ReLU(), torch.nn.Linear(2*emb_dim, emb_dim))
### Mapping 0/1 edge features to embedding
self.edge_encoder = torch.nn.Linear(9, emb_dim)
### Mapping uniform input features to embedding.
self.input_layer = input_layer
if self.input_layer:
self.input_node_embeddings = torch.nn.Embedding(2, emb_dim)
torch.nn.init.xavier_uniform_(self.input_node_embeddings.weight.data)
self.aggr = aggr
def forward(self, x, edge_index, edge_attr):
#add self loops in the edge space
edge_index = add_self_loops(edge_index, num_nodes = x.size(0))
# print(edge_index[0])
# print(edge_index[1])
#add features corresponding to self-loop edges.
self_loop_attr = torch.zeros(x.size(0), 9)
self_loop_attr[:,7] = 1 # attribute for self-loop edge
self_loop_attr = self_loop_attr.to(edge_attr.device).to(edge_attr.dtype)
edge_attr = torch.cat((edge_attr, self_loop_attr), dim = 0)
edge_embeddings = self.edge_encoder(edge_attr)
if self.input_layer:
x = self.input_node_embeddings(x.to(torch.int64).view(-1,))
#return self.propagate(self.aggr, edge_index, x=x, edge_attr=edge_embeddings)
return self.propagate(edge_index[0], x=x, edge_attr=edge_embeddings)
def message(self, x_j, edge_attr):
return torch.cat([x_j, edge_attr], dim = 1)
def update(self, aggr_out):
return self.mlp(aggr_out)
class GCNConv(MessagePassing):
def __init__(self, emb_dim, aggr = "add", input_layer = False):
super(GCNConv, self).__init__()
self.emb_dim = emb_dim
self.linear = torch.nn.Linear(emb_dim, emb_dim)
### Mapping 0/1 edge features to embedding
self.edge_encoder = torch.nn.Linear(9, emb_dim)
### Mapping uniform input features to embedding.
self.input_layer = input_layer
if self.input_layer:
self.input_node_embeddings = torch.nn.Embedding(2, emb_dim)
torch.nn.init.xavier_uniform_(self.input_node_embeddings.weight.data)
self.aggr = aggr
def norm(self, edge_index, num_nodes, dtype):
### assuming that self-loops have been already added in edge_index
edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype,
device=edge_index.device)
row, col = edge_index
deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0
return deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]
def forward(self, x, edge_index, edge_attr):
#add self loops in the edge space
edge_index = add_self_loops(edge_index, num_nodes = x.size(0))
#add features corresponding to self-loop edges.
self_loop_attr = torch.zeros(x.size(0), 9)
self_loop_attr[:,7] = 1 # attribute for self-loop edge
self_loop_attr = self_loop_attr.to(edge_attr.device).to(edge_attr.dtype)
edge_attr = torch.cat((edge_attr, self_loop_attr), dim = 0)
edge_embeddings = self.edge_encoder(edge_attr)
if self.input_layer:
x = self.input_node_embeddings(x.to(torch.int64).view(-1,))
norm = self.norm(edge_index, x.size(0), x.dtype)
x = self.linear(x)
return self.propagate(self.aggr, edge_index, x=x, edge_attr=edge_embeddings, norm = norm)
def message(self, x_j, edge_attr, norm):
return norm.view(-1, 1) * (x_j + edge_attr)
class GATConv(MessagePassing):
def __init__(self, emb_dim, heads=2, negative_slope=0.2, aggr = "add", input_layer = False):
super(GATConv, self).__init__()
self.aggr = aggr
self.emb_dim = emb_dim
self.heads = heads
self.negative_slope = negative_slope
self.weight_linear = torch.nn.Linear(emb_dim, heads * emb_dim)
self.att = torch.nn.Parameter(torch.Tensor(1, heads, 2 * emb_dim))
self.bias = torch.nn.Parameter(torch.Tensor(emb_dim))
### Mapping 0/1 edge features to embedding
self.edge_encoder = torch.nn.Linear(9, heads * emb_dim)
### Mapping uniform input features to embedding.
self.input_layer = input_layer
if self.input_layer:
self.input_node_embeddings = torch.nn.Embedding(2, emb_dim)
torch.nn.init.xavier_uniform_(self.input_node_embeddings.weight.data)
self.reset_parameters()
def reset_parameters(self):
glorot(self.att)
zeros(self.bias)
def forward(self, x, edge_index, edge_attr):
#add self loops in the edge space
edge_index = add_self_loops(edge_index, num_nodes = x.size(0))
#add features corresponding to self-loop edges.
self_loop_attr = torch.zeros(x.size(0), 9)
self_loop_attr[:,7] = 1 # attribute for self-loop edge
self_loop_attr = self_loop_attr.to(edge_attr.device).to(edge_attr.dtype)
edge_attr = torch.cat((edge_attr, self_loop_attr), dim = 0)
edge_embeddings = self.edge_encoder(edge_attr)
if self.input_layer:
x = self.input_node_embeddings(x.to(torch.int64).view(-1,))
x = self.weight_linear(x).view(-1, self.heads, self.emb_dim)
return self.propagate(self.aggr, edge_index, x=x, edge_attr=edge_embeddings)
def message(self, edge_index, x_i, x_j, edge_attr):
edge_attr = edge_attr.view(-1, self.heads, self.emb_dim)
x_j += edge_attr
alpha = (torch.cat([x_i, x_j], dim=-1) * self.att).sum(dim=-1)
alpha = F.leaky_relu(alpha, self.negative_slope)
alpha = softmax(alpha, edge_index[0])
return x_j * alpha.view(-1, self.heads, 1)
def update(self, aggr_out):
aggr_out = aggr_out.mean(dim=1)
aggr_out = aggr_out + self.bias
return aggr_out
class GraphSAGEConv(MessagePassing):
def __init__(self, emb_dim, aggr = "mean", input_layer = False):
super(GraphSAGEConv, self).__init__()
self.emb_dim = emb_dim
self.linear = torch.nn.Linear(emb_dim, emb_dim)
### Mapping 0/1 edge features to embedding
self.edge_encoder = torch.nn.Linear(9, emb_dim)
### Mapping uniform input features to embedding.
self.input_layer = input_layer
if self.input_layer:
self.input_node_embeddings = torch.nn.Embedding(2, emb_dim)
torch.nn.init.xavier_uniform_(self.input_node_embeddings.weight.data)
self.aggr = aggr
def forward(self, x, edge_index, edge_attr):
#add self loops in the edge space
edge_index = add_self_loops(edge_index, num_nodes = x.size(0))
#add features corresponding to self-loop edges.
self_loop_attr = torch.zeros(x.size(0), 9)
self_loop_attr[:,7] = 1 # attribute for self-loop edge
self_loop_attr = self_loop_attr.to(edge_attr.device).to(edge_attr.dtype)
edge_attr = torch.cat((edge_attr, self_loop_attr), dim = 0)
edge_embeddings = self.edge_encoder(edge_attr)
if self.input_layer:
x = self.input_node_embeddings(x.to(torch.int64).view(-1,))
x = self.linear(x)
return self.propagate(self.aggr, edge_index, x=x, edge_attr=edge_embeddings)
def message(self, x_j, edge_attr):
return x_j + edge_attr
def update(self, aggr_out):
return F.normalize(aggr_out, p = 2, dim = -1)
class GNN(torch.nn.Module):
def __init__(self, num_layer, emb_dim, JK = "last", drop_ratio = 0, gnn_type = "gin"):
super(GNN, self).__init__()
self.num_layer = num_layer
self.drop_ratio = drop_ratio
self.JK = JK
if self.num_layer < 2:
raise ValueError("Number of GNN layers must be greater than 1.")
###List of message-passing GNN convs
self.gnns = torch.nn.ModuleList()
for layer in range(num_layer):
if layer == 0:
input_layer = True
else:
input_layer = False
if gnn_type == "gin":
self.gnns.append(GINConv(emb_dim, aggr = "add", input_layer = input_layer))
elif gnn_type == "gcn":
self.gnns.append(GCNConv(emb_dim, input_layer = input_layer))
elif gnn_type == "gat":
self.gnns.append(GATConv(emb_dim, input_layer = input_layer))
elif gnn_type == "graphsage":
self.gnns.append(GraphSAGEConv(emb_dim, input_layer = input_layer))
#增加num_layer层以求获取更为通用的图嵌入,企图获得结构方面的信息
for layer in range(num_layer):
if gnn_type == "gin":
self.gnns.append(GINConv(emb_dim, aggr="add", input_layer=input_layer))
elif gnn_type == "gcn":
self.gnns.append(GCNConv(emb_dim, input_layer=input_layer))
elif gnn_type == "gat":
self.gnns.append(GATConv(emb_dim, input_layer=input_layer))
elif gnn_type == "graphsage":
self.gnns.append(GraphSAGEConv(emb_dim, input_layer=input_layer))
###List of batchnorms
# self.batch_norms = torch.nn.ModuleList()
# for layer in range(2 * num_layer):
# self.batch_norms.append(torch.nn.BatchNorm1d(emb_dim))
def forward(self, x, edge_index, edge_attr):
h_node_list = [x]
h_struct_list=[x]
for layer in range(self.num_layer):
h_node = self.gnns[layer](h_node_list[layer], edge_index, edge_attr)
#h_node = self.batch_norms[layer](h_node)
if layer == self.num_layer - 1:
#remove relu from the last layer
h_node = F.dropout(h_node, self.drop_ratio, training = self.training)
else:
h_node = F.dropout(F.relu(h_node), self.drop_ratio, training = self.training)
h_node_list.append(h_node)
for layer in range(self.num_layer*2):
h_struct=self.gnns[layer](h_struct_list[layer], edge_index, edge_attr)
#h_struct = self.batch_norms[layer](h_struct)
if layer == self.num_layer*2 - 1 :
# remove relu from the last layer
h_struct = F.dropout(h_struct, self.drop_ratio, training=self.training)
else:
h_struct = F.dropout(F.relu(h_struct), self.drop_ratio, training=self.training)
h_struct_list.append(h_struct)
if self.JK == "last":
node_representation = h_node_list[-1]
struct_representation=h_struct_list[-1]
elif self.JK == "sum":
h_node_list = [h.unsqueeze_(0) for h in h_node_list]
node_representation = torch.sum(torch.cat(h_node_list[1:], dim = 0), dim = 0)[0]
h_struct_list = [h.unsqueeze_(0) for h in h_struct_list]
struct_representation=torch.sum(torch.cat(h_struct_list[1:], dim = 0), dim = 0)[0]
return node_representation,struct_representation
class GNN_structpred(torch.nn.Module):
def __init__(self, num_layer, emb_dim, JK="last", drop_ratio=0, gnn_type="gin",cluster_number=5):
super(GNN_structpred, self).__init__()
self.num_layer = num_layer
self.drop_ratio = drop_ratio
self.JK = JK
self.emb_dim = emb_dim
self.cluster_number=cluster_number
if self.num_layer < 2:
raise ValueError("Number of GNN layers must be greater than 1.")
self.gnn = GNN(num_layer, emb_dim, JK, drop_ratio, gnn_type=gnn_type)
self.struct_pred_linear = torch.nn.Linear(self.emb_dim, self.cluster_number)
# print(self.graph_pred_linear.weight.data)
def from_pretrained(self, model_file):
self.gnn.load_state_dict(torch.load(model_file, map_location=lambda storage, loc: storage))
def forward(self, data):
x, edge_index, edge_attr, batch = data.x, data.edge_index, data.edge_attr, data.batch
_, struct_representation = self.gnn(x, edge_index, edge_attr)
return self.struct_pred_linear(struct_representation)
class GNN_structpred_node(torch.nn.Module):
def __init__(self, num_layer, emb_dim, JK="last", drop_ratio=0, gnn_type="gin",cluster_number=5):
super(GNN_structpred_node, self).__init__()
self.num_layer = num_layer
self.drop_ratio = drop_ratio
self.JK = JK
self.emb_dim = emb_dim
self.cluster_number=cluster_number
if self.num_layer < 2:
raise ValueError("Number of GNN layers must be greater than 1.")
self.gnn = GNN(num_layer, emb_dim, JK, drop_ratio, gnn_type=gnn_type)
self.struct_pred_linear = torch.nn.Linear(self.emb_dim, self.cluster_number)
# print(self.graph_pred_linear.weight.data)
def from_pretrained(self, model_file):
self.gnn.load_state_dict(torch.load(model_file, map_location=lambda storage, loc: storage))
def forward(self, data):
x, edge_index, edge_attr, batch = data.x, data.edge_index, data.edge_attr, data.batch
node_representation, _ = self.gnn(x, edge_index, edge_attr)
return self.struct_pred_linear(node_representation)
class GNN_graphpred(torch.nn.Module):
"""
Extension of GIN to incorporate edge information by concatenation.
Args:
num_layer (int): the number of GNN layers
emb_dim (int): dimensionality of embeddings
num_tasks (int): number of tasks in multi-task learning scenario
drop_ratio (float): dropout rate
JK (str): last, concat, max or sum.
graph_pooling (str): sum, mean, max, attention, set2set
See https://arxiv.org/abs/1810.00826
JK-net: https://arxiv.org/abs/1806.03536
"""
def __init__(self, num_layer, emb_dim, num_tasks, JK = "last", drop_ratio = 0, graph_pooling = "mean", gnn_type = "gin"):
super(GNN_graphpred, self).__init__()
self.num_layer = num_layer
self.drop_ratio = drop_ratio
self.JK = JK
self.emb_dim = emb_dim
self.num_tasks = num_tasks
if self.num_layer < 2:
raise ValueError("Number of GNN layers must be greater than 1.")
self.gnn = GNN(num_layer, emb_dim, JK, drop_ratio, gnn_type = gnn_type)
#Different kind of graph pooling
if graph_pooling == "sum":
self.pool = global_add_pool
elif graph_pooling == "mean":
self.pool = global_mean_pool
elif graph_pooling == "max":
self.pool = global_max_pool
elif graph_pooling == "attention":
self.pool = GlobalAttention(gate_nn = torch.nn.Linear(emb_dim, 1))
else:
raise ValueError("Invalid graph pooling type.")
self.graph_pred_linear = torch.nn.Linear(4*self.emb_dim, self.num_tasks)
# print(self.graph_pred_linear.weight.data)
def from_pretrained(self, model_file):
self.gnn.load_state_dict(torch.load(model_file, map_location=lambda storage, loc: storage))
def forward(self, data):
x, edge_index, edge_attr, batch = data.x, data.edge_index, data.edge_attr, data.batch
node_representation,struct_representation = self.gnn(x, edge_index, edge_attr)
node_pooled = self.pool(node_representation, batch)
struct_pooled= self.pool(struct_representation, batch)
center_node_rep = node_representation[data.center_node_idx]
center_struct_rep = struct_representation[data.center_node_idx]
graph_rep = torch.cat([node_pooled,struct_pooled,center_node_rep,center_struct_rep], dim= 1)
return self.graph_pred_linear(graph_rep)
if __name__ == "__main__":
pass