-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTDPlusModel.py
More file actions
279 lines (214 loc) · 9.31 KB
/
TDPlusModel.py
File metadata and controls
279 lines (214 loc) · 9.31 KB
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
import torch
from typing import Callable, Optional
from torch.nn import Parameter
from torch_geometric.nn import MessagePassing
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import add_self_loops, degree
from scipy.special import factorial
from torch_geometric.data import Data, InMemoryDataset
from torch.nn import ModuleList, Dropout, ReLU, ELU
from typing import List
from args import get_citation_args
class TDPlusConv(MessagePassing):
def __init__(self, in_channels, init_t):
super(TDPlusConv, self).__init__(aggr='add') # "Add" aggregation (Step 5).
args = get_citation_args()
self.init_t = init_t
self.step = 10
if not args.denseT:
self.t = Parameter(torch.Tensor(self.step, in_channels))
else:
self.t = Parameter(torch.Tensor(self.step))
# self.t.data.fill_(2)
self.reset_parameters()
# self.t.requires_grad = False
def forward(self, x, edge_index, edge_weight=None):
# x has shape [N, in_channels]
# edge_index has shape [2, E]
# print(self.t)
# Step 1: Add self-loops to the adjacency matrix.
self.t_norm = torch.nn.functional.softmax(self.t, dim=0)
edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
# Step 2: Linearly transform node feature matrix.
# Step 3: Compute normalization.
row, col = edge_index
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]
# Step 4-5: Start propagating messages.
x_list = [0 for i in range(self.step)]
x_list[0] = x
for i in range(1, self.step):
x_list[i] = self.propagate(edge_index, x=x_list[i - 1], norm=norm)
y = 0
for k in range(self.step):
x_list[k] = self.t_norm[k] * x_list[k] ## important!
# x_list[k] = torch.pow(self.t, k) / factorial(k) * x_list[k]
if k != 0:
y += x_list[k]
else:
y = x_list[k]
return y
def reset_parameters(self):
torch.nn.init.constant_(self.t, self.init_t)
#self.t.requires_grad = False
def message(self, x_j, norm):
# x_j has shape [E, out_channels]
# Step 4: Normalize node features.
return norm.view(-1, 1) * x_j
class GCNPlusConv(torch.nn.Module):
def __init__(self, in_channels, out_channels, init_t):
super(GCNPlusConv, self).__init__()
self.diffusion = TDPlusConv(in_channels, init_t)
self.lin = torch.nn.Linear(in_channels, out_channels)
def forward(self, x, edge_index, edge_weight=None):
x = self.diffusion(x, edge_index)
x = self.lin(x)
return x
def reset_parameters(self):
self.lin.reset_parameters()
self.diffusion.reset_parameters()
class ARMAPlusConv(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, init_t: float,
num_stacks: int = 1, num_layers: int = 1,
shared_weights: bool = False,
act: Optional[Callable] = ReLU(), dropout: float = 0.,
bias: bool = True):
super(ARMAPlusConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.num_stacks = num_stacks
self.num_layers = num_layers
self.act = act
self.shared_weights = shared_weights
assert(num_layers == 1)
self.diffusion = TDPlusConv(in_channels, init_t)
K, T, F_in, F_out = num_stacks, num_layers, in_channels, out_channels
self.init_weight = Parameter(torch.Tensor(K, F_in, F_out))
self.root_weight = Parameter(torch.Tensor(T, K, F_in, F_out))
self.bias = Parameter(torch.Tensor(T, K, 1, F_out))
self.dropout = Dropout(p=dropout)
self.reset_parameters()
def forward(self, x, edge_index, edge_weight=None):
# edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
# # Step 2: Linearly transform node feature matrix.
# # Step 3: Compute normalization.
# row, col = edge_index
# deg = degree(col, x.size(0), dtype=x.dtype)
# deg_inv_sqrt = deg.pow(-0.5)
# norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]
x = self.diffusion(x, edge_index)
x = x.unsqueeze(-3)
out = x
out = out @ self.init_weight
root = self.dropout(x)
out += root @ self.root_weight[0]
out += self.bias[0]
out = self.act(out)
return out.mean(dim=-3)
def reset_parameters(self):
glorot(self.init_weight)
glorot(self.root_weight)
zeros(self.bias)
self.diffusion.reset_parameters()
# def message(self, x_j, norm):
# # x_j has shape [E, out_channels]
# # Step 4: Normalize node features.
# return norm.view(-1, 1) * x_j
class GCN(torch.nn.Module):
def __init__(self,
dataset: InMemoryDataset,
t: float,
hidden: List[int] = [64],
dropout: float = 0.5):
super(GCN, self).__init__()
num_features = [dataset.data.x.shape[1]] + hidden + [dataset.num_classes]
layers = []
for in_features, out_features in zip(num_features[:-1], num_features[1:]):
# layers.append(SGConv(in_features, out_features, K=2))
layers.append(GCNPlusConv(in_features, out_features, init_t=t))
self.layers = ModuleList(layers)
# self.reg_params = list(layers[0].parameters())
# self.non_reg_params = list([p for l in layers[1:] for p in l.parameters()])
self.dropout = Dropout(p=dropout)
self.act_fn = ReLU()
def reset_parameters(self):
for layer in self.layers:
layer.reset_parameters()
def forward(self, data: Data):
x, edge_index, edge_attr = data.x, data.edge_index, data.edge_attr
for i, layer in enumerate(self.layers):
x = layer(x, edge_index, edge_weight=edge_attr)
if i == len(self.layers) - 1:
break
x = self.act_fn(x)
x = self.dropout(x)
return torch.nn.functional.log_softmax(x, dim=1)
class JKNet(torch.nn.Module):
def __init__(self,
dataset: InMemoryDataset,
t: float,
hidden: List[int] = [64],
dropout: float = 0.5):
super(JKNet, self).__init__()
args = get_citation_args()
num_features = [dataset.data.x.shape[1]] + hidden
layers = []
for in_features, out_features in zip(num_features[:-1], num_features[1:]):
layers.append(GCNPlusConv(in_features, out_features, init_t=t))
layers.append(torch.nn.Linear(sum(hidden), dataset.num_classes))
self.layers = ModuleList(layers)
# self.reg_params = list(layers[0].parameters())
# self.non_reg_params = list([p for l in layers[1:] for p in l.parameters()])
if args.shareT == True:
for num in range(len(layers)):
self.layers[num].diffusion = self.layers[0].diffusion
self.dropout = Dropout(p=dropout)
self.act_fn = ReLU()
def reset_parameters(self):
for layer in self.layers:
layer.reset_parameters()
def forward(self, data: Data):
x, edge_index, edge_attr = data.x, data.edge_index, data.edge_attr
layer_outputs = []
for i, layer in enumerate(self.layers[:-1]):
x = layer(x, edge_index, edge_weight=edge_attr)
x = self.act_fn(x)
x = self.dropout(x)
layer_outputs.append(x)
x = torch.cat(layer_outputs, dim=1)
x = self.layers[-1](x)
return torch.nn.functional.log_softmax(x, dim=1)
class ARMA(torch.nn.Module):
def __init__(self,
dataset: InMemoryDataset,
t: float,
stacks: int,
hidden: List[int] = [64],
dropout: float = 0.5):
super(ARMA, self).__init__()
args = get_citation_args()
num_features = [dataset.data.x.shape[1]] + hidden + [dataset.num_classes]
layers = []
for in_features, out_features in zip(num_features[:-1], num_features[1:]):
layers.append(ARMAPlusConv(in_features, out_features, init_t = t, num_stacks = stacks, num_layers = 1, shared_weights = False, dropout = dropout))
self.layers = ModuleList(layers)
if args.shareT == True:
for num in range(len(layers)):
self.layers[num].diffusion = self.layers[0].diffusion
# self.reg_params = list(layers[0].parameters())
# self.non_reg_params = list([p for l in layers[1:] for p in l.parameters()])
self.dropout = Dropout(p=dropout)
self.act_fn = ReLU()
def reset_parameters(self):
for layer in self.layers:
layer.reset_parameters()
def forward(self, data: Data):
x, edge_index, edge_attr = data.x, data.edge_index, data.edge_attr
for i, layer in enumerate(self.layers):
x = layer(x, edge_index, edge_weight=edge_attr)
if i == len(self.layers) - 1:
break
x = self.act_fn(x)
x = self.dropout(x)
return torch.nn.functional.log_softmax(x, dim=1)