-
Notifications
You must be signed in to change notification settings - Fork 3
/
pyg_gnn_layer.py
185 lines (159 loc) · 7.35 KB
/
pyg_gnn_layer.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
import torch
import torch.nn.functional as F
from torch.nn import Parameter
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import remove_self_loops, add_self_loops, add_remaining_self_loops, softmax
from torch_scatter import scatter_add
from message_passing import MessagePassing
#from torch_geometric.nn.conv import MessagePassing
class GeoLayer(MessagePassing):
def __init__(self,
in_channels,
out_channels,
heads=1,
concat=True,
negative_slope=0.2,
dropout=0,
bias=True,
att_type="gat",
agg_type="sum",
pool_dim=0):
if agg_type in ["sum", "mlp"]:
super(GeoLayer, self).__init__('add')
elif agg_type in ["mean", "max"]:
super(GeoLayer, self).__init__(agg_type)
self.in_channels = in_channels
self.out_channels = out_channels
self.heads = heads
self.concat = concat
self.negative_slope = negative_slope
self.dropout = dropout
self.att_type = att_type
self.agg_type = agg_type
# GCN weight
#self.gcn_weight = None
self.weight = Parameter(torch.Tensor(in_channels, heads * out_channels))
self.att = Parameter(torch.Tensor(1, heads, 2 * out_channels))
if bias and concat:
self.bias = Parameter(torch.Tensor(heads * out_channels))
elif bias and not concat:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
if self.att_type in ["generalized_linear"]:
self.general_att_layer = torch.nn.Linear(out_channels, 1, bias=False)
#if self.agg_type in ["mean", "max", "mlp"]:
# if pool_dim <= 0:
# pool_dim = 128
#self.pool_dim = pool_dim
#if pool_dim != 0:
# self.pool_layer = torch.nn.ModuleList()
# self.pool_layer.append(torch.nn.Linear(self.out_channels, self.pool_dim))
# self.pool_layer.append(torch.nn.Linear(self.pool_dim, self.out_channels))
#else:
# pass
self.reset_parameters()
@staticmethod
def norm(edge_index, num_nodes, edge_weight, improved=False, dtype=None):
if edge_weight is None:
edge_weight = torch.ones((edge_index.size(1), ),
dtype=dtype,
device=edge_index.device)
fill_value = 1 if not improved else 2
edge_index, edge_weight = add_remaining_self_loops(
edge_index, edge_weight, fill_value, num_nodes)
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 edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]
def reset_parameters(self):
glorot(self.weight)
glorot(self.att)
zeros(self.bias)
if self.att_type in ["generalized_linear"]:
glorot(self.general_att_layer.weight)
#if self.pool_dim != 0:
# for layer in self.pool_layer:
# glorot(layer.weight)
# zeros(layer.bias)
def forward(self, x, edge_index, size=None):
""""""
if size is None and torch.is_tensor(x):
edge_index, _ = remove_self_loops(edge_index)
edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
# prepare
if torch.is_tensor(x):
x = torch.mm(x, self.weight).view(-1, self.heads, self.out_channels)
else:
x = (None if x[0] is None else torch.matmul(x[0], self.weight).view(-1, self.heads, self.out_channels),
None if x[1] is None else torch.matmul(x[1], self.weight).view(-1, self.heads, self.out_channels))
num_nodes = x.size(0) if torch.is_tensor(x) else size[0]
return self.propagate(edge_index, size=size, x=x, num_nodes=num_nodes)
def message(self, x_i, x_j, edge_index, num_nodes):
if self.att_type == "const":
if self.training and self.dropout > 0:
x_j = F.dropout(x_j, p=self.dropout, training=True)
neighbor = x_j
#elif self.att_type == "gcn":
# if self.gcn_weight is None or self.gcn_weight.size(0) != x_j.size(0): # 对于不同的图gcn_weight需要重新计算
# _, norm = self.norm(edge_index, num_nodes, None)
# self.gcn_weight = norm
# neighbor = self.gcn_weight.view(-1, 1, 1) * x_j
else:
# Compute attention coefficients.
alpha = self.apply_attention(edge_index, num_nodes, x_i, x_j)
alpha = softmax(alpha, edge_index[0], ptr=None, num_nodes=num_nodes)
# Sample attention coefficients stochastically.
if self.training and self.dropout > 0:
alpha = F.dropout(alpha, p=self.dropout, training=True)
neighbor = x_j * alpha.view(-1, self.heads, 1)
#if self.pool_dim > 0:
# for layer in self.pool_layer:
# neighbor = layer(neighbor)
return neighbor
def apply_attention(self, edge_index, num_nodes, x_i, x_j):
if self.att_type == "gat":
alpha = (torch.cat([x_i, x_j], dim=-1) * self.att).sum(dim=-1)
alpha = F.leaky_relu(alpha, self.negative_slope)
elif self.att_type == "gat_sym":
wl = self.att[:, :, :self.out_channels] # weight left
wr = self.att[:, :, self.out_channels:] # weight right
alpha = (x_i * wl).sum(dim=-1) + (x_j * wr).sum(dim=-1)
alpha_2 = (x_j * wl).sum(dim=-1) + (x_i * wr).sum(dim=-1)
alpha = F.leaky_relu(alpha, self.negative_slope) + F.leaky_relu(alpha_2, self.negative_slope)
elif self.att_type == "linear":
wl = self.att[:, :, :self.out_channels] # weight left
wr = self.att[:, :, self.out_channels:] # weight right
al = x_j * wl
ar = x_j * wr
alpha = al.sum(dim=-1) + ar.sum(dim=-1)
alpha = torch.tanh(alpha)
elif self.att_type == "cos":
wl = self.att[:, :, :self.out_channels] # weight left
wr = self.att[:, :, self.out_channels:] # weight right
alpha = x_i * wl * x_j * wr
alpha = alpha.sum(dim=-1)
elif self.att_type == "generalized_linear":
wl = self.att[:, :, :self.out_channels] # weight left
wr = self.att[:, :, self.out_channels:] # weight right
al = x_i * wl
ar = x_j * wr
alpha = al + ar
alpha = torch.tanh(alpha)
alpha = self.general_att_layer(alpha)
else:
raise Exception("Wrong attention type:", self.att_type)
return alpha
def update(self, aggr_out):
if self.concat is True:
aggr_out = aggr_out.view(-1, self.heads * self.out_channels)
else:
aggr_out = aggr_out.mean(dim=1)
if self.bias is not None:
aggr_out = aggr_out + self.bias
return aggr_out
def __repr__(self):
return '{}({}, {}, heads={})'.format(self.__class__.__name__,
self.in_channels,
self.out_channels, self.heads)