-
Notifications
You must be signed in to change notification settings - Fork 20
/
model.py
404 lines (302 loc) · 11.7 KB
/
model.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
import torch
import torch.nn.functional as F
import torch.nn as nn
class gcn_operation(nn.Module):
def __init__(self, adj, in_dim, out_dim, num_vertices, activation='GLU'):
"""
图卷积模块
:param adj: 邻接图
:param in_dim: 输入维度
:param out_dim: 输出维度
:param num_vertices: 节点数量
:param activation: 激活方式 {'relu', 'GLU'}
"""
super(gcn_operation, self).__init__()
self.adj = adj
self.in_dim = in_dim
self.out_dim = out_dim
self.num_vertices = num_vertices
self.activation = activation
assert self.activation in {'GLU', 'relu'}
if self.activation == 'GLU':
self.FC = nn.Linear(self.in_dim, 2 * self.out_dim, bias=True)
else:
self.FC = nn.Linear(self.in_dim, self.out_dim, bias=True)
def forward(self, x, mask=None):
"""
:param x: (3*N, B, Cin)
:param mask:(3*N, 3*N)
:return: (3*N, B, Cout)
"""
adj = self.adj
if mask is not None:
adj = adj.to(mask.device) * mask
x = torch.einsum('nm, mbc->nbc', adj.to(x.device), x) # 3*N, B, Cin
if self.activation == 'GLU':
lhs_rhs = self.FC(x) # 3*N, B, 2*Cout
lhs, rhs = torch.split(lhs_rhs, self.out_dim, dim=-1) # 3*N, B, Cout
out = lhs * torch.sigmoid(rhs)
del lhs, rhs, lhs_rhs
return out
elif self.activation == 'relu':
return torch.relu(self.FC(x)) # 3*N, B, Cout
class STSGCM(nn.Module):
def __init__(self, adj, in_dim, out_dims, num_of_vertices, activation='GLU'):
"""
:param adj: 邻接矩阵
:param in_dim: 输入维度
:param out_dims: list 各个图卷积的输出维度
:param num_of_vertices: 节点数量
:param activation: 激活方式 {'relu', 'GLU'}
"""
super(STSGCM, self).__init__()
self.adj = adj
self.in_dim = in_dim
self.out_dims = out_dims
self.num_of_vertices = num_of_vertices
self.activation = activation
self.gcn_operations = nn.ModuleList()
self.gcn_operations.append(
gcn_operation(
adj=self.adj,
in_dim=self.in_dim,
out_dim=self.out_dims[0],
num_vertices=self.num_of_vertices,
activation=self.activation
)
)
for i in range(1, len(self.out_dims)):
self.gcn_operations.append(
gcn_operation(
adj=self.adj,
in_dim=self.out_dims[i-1],
out_dim=self.out_dims[i],
num_vertices=self.num_of_vertices,
activation=self.activation
)
)
def forward(self, x, mask=None):
"""
:param x: (3N, B, Cin)
:param mask: (3N, 3N)
:return: (N, B, Cout)
"""
need_concat = []
for i in range(len(self.out_dims)):
x = self.gcn_operations[i](x, mask)
need_concat.append(x)
# shape of each element is (1, N, B, Cout)
need_concat = [
torch.unsqueeze(
h[self.num_of_vertices: 2 * self.num_of_vertices], dim=0
) for h in need_concat
]
out = torch.max(torch.cat(need_concat, dim=0), dim=0).values # (N, B, Cout)
del need_concat
return out
class STSGCL(nn.Module):
def __init__(self,
adj,
history,
num_of_vertices,
in_dim,
out_dims,
strides=3,
activation='GLU',
temporal_emb=True,
spatial_emb=True):
"""
:param adj: 邻接矩阵
:param history: 输入时间步长
:param in_dim: 输入维度
:param out_dims: list 各个图卷积的输出维度
:param strides: 滑动窗口步长,local时空图使用几个时间步构建的,默认为3
:param num_of_vertices: 节点数量
:param activation: 激活方式 {'relu', 'GLU'}
:param temporal_emb: 加入时间位置嵌入向量
:param spatial_emb: 加入空间位置嵌入向量
"""
super(STSGCL, self).__init__()
self.adj = adj
self.strides = strides
self.history = history
self.in_dim = in_dim
self.out_dims = out_dims
self.num_of_vertices = num_of_vertices
self.activation = activation
self.temporal_emb = temporal_emb
self.spatial_emb = spatial_emb
self.STSGCMS = nn.ModuleList()
for i in range(self.history - self.strides + 1):
self.STSGCMS.append(
STSGCM(
adj=self.adj,
in_dim=self.in_dim,
out_dims=self.out_dims,
num_of_vertices=self.num_of_vertices,
activation=self.activation
)
)
if self.temporal_emb:
self.temporal_embedding = nn.Parameter(torch.FloatTensor(1, self.history, 1, self.in_dim))
# 1, T, 1, Cin
if self.spatial_emb:
self.spatial_embedding = nn.Parameter(torch.FloatTensor(1, 1, self.num_of_vertices, self.in_dim))
# 1, 1, N, Cin
self.reset()
def reset(self):
if self.temporal_emb:
nn.init.xavier_normal_(self.temporal_embedding, gain=0.0003)
if self.spatial_emb:
nn.init.xavier_normal_(self.spatial_embedding, gain=0.0003)
def forward(self, x, mask=None):
"""
:param x: B, T, N, Cin
:param mask: (N, N)
:return: B, T-2, N, Cout
"""
if self.temporal_emb:
x = x + self.temporal_embedding
if self.spatial_emb:
x = x + self.spatial_embedding
need_concat = []
batch_size = x.shape[0]
for i in range(self.history - self.strides + 1):
t = x[:, i: i+self.strides, :, :] # (B, 3, N, Cin)
t = torch.reshape(t, shape=[batch_size, self.strides * self.num_of_vertices, self.in_dim])
# (B, 3*N, Cin)
t = self.STSGCMS[i](t.permute(1, 0, 2), mask) # (3*N, B, Cin) -> (N, B, Cout)
t = torch.unsqueeze(t.permute(1, 0, 2), dim=1) # (N, B, Cout) -> (B, N, Cout) ->(B, 1, N, Cout)
need_concat.append(t)
out = torch.cat(need_concat, dim=1) # (B, T-2, N, Cout)
del need_concat, batch_size
return out
class output_layer(nn.Module):
def __init__(self, num_of_vertices, history, in_dim,
hidden_dim=128, horizon=12):
"""
预测层,注意在作者的实验中是对每一个预测时间step做处理的,也即他会令horizon=1
:param num_of_vertices:节点数
:param history:输入时间步长
:param in_dim: 输入维度
:param hidden_dim:中间层维度
:param horizon:预测时间步长
"""
super(output_layer, self).__init__()
self.num_of_vertices = num_of_vertices
self.history = history
self.in_dim = in_dim
self.hidden_dim = hidden_dim
self.horizon = horizon
self.FC1 = nn.Linear(self.in_dim * self.history, self.hidden_dim, bias=True)
self.FC2 = nn.Linear(self.hidden_dim, self.horizon, bias=True)
def forward(self, x):
"""
:param x: (B, Tin, N, Cin)
:return: (B, Tout, N)
"""
batch_size = x.shape[0]
x = x.permute(0, 2, 1, 3) # B, N, Tin, Cin
out1 = torch.relu(self.FC1(x.reshape(batch_size, self.num_of_vertices, -1)))
# (B, N, Tin, Cin) -> (B, N, Tin * Cin) -> (B, N, hidden)
out2 = self.FC2(out1) # (B, N, hidden) -> (B, N, horizon)
del out1, batch_size
return out2.permute(0, 2, 1) # B, horizon, N
class STSGCN(nn.Module):
def __init__(self, adj, history, num_of_vertices, in_dim, hidden_dims,
first_layer_embedding_size, out_layer_dim, activation='GLU', use_mask=True,
temporal_emb=True, spatial_emb=True, horizon=12, strides=3):
"""
:param adj: local时空间矩阵
:param history:输入时间步长
:param num_of_vertices:节点数量
:param in_dim:输入维度
:param hidden_dims: lists, 中间各STSGCL层的卷积操作维度
:param first_layer_embedding_size: 第一层输入层的维度
:param out_layer_dim: 输出模块中间层维度
:param activation: 激活函数 {relu, GlU}
:param use_mask: 是否使用mask矩阵对adj进行优化
:param temporal_emb:是否使用时间嵌入向量
:param spatial_emb:是否使用空间嵌入向量
:param horizon:预测时间步长
:param strides:滑动窗口步长,local时空图使用几个时间步构建的,默认为3
"""
super(STSGCN, self).__init__()
self.adj = adj
self.num_of_vertices = num_of_vertices
self.hidden_dims = hidden_dims
self.out_layer_dim = out_layer_dim
self.activation = activation
self.use_mask = use_mask
self.temporal_emb = temporal_emb
self.spatial_emb = spatial_emb
self.horizon = horizon
self.strides = strides
self.First_FC = nn.Linear(in_dim, first_layer_embedding_size, bias=True)
self.STSGCLS = nn.ModuleList()
self.STSGCLS.append(
STSGCL(
adj=self.adj,
history=history,
num_of_vertices=self.num_of_vertices,
in_dim=first_layer_embedding_size,
out_dims=self.hidden_dims[0],
strides=self.strides,
activation=self.activation,
temporal_emb=self.temporal_emb,
spatial_emb=self.spatial_emb
)
)
in_dim = self.hidden_dims[0][-1]
history -= (self.strides - 1)
for idx, hidden_list in enumerate(self.hidden_dims):
if idx == 0:
continue
self.STSGCLS.append(
STSGCL(
adj=self.adj,
history=history,
num_of_vertices=self.num_of_vertices,
in_dim=in_dim,
out_dims=hidden_list,
strides=self.strides,
activation=self.activation,
temporal_emb=self.temporal_emb,
spatial_emb=self.spatial_emb
)
)
history -= (self.strides - 1)
in_dim = hidden_list[-1]
self.predictLayer = nn.ModuleList()
for t in range(self.horizon):
self.predictLayer.append(
output_layer(
num_of_vertices=self.num_of_vertices,
history=history,
in_dim=in_dim,
hidden_dim=out_layer_dim,
horizon=1
)
)
if self.use_mask:
mask = torch.zeros_like(self.adj)
mask[self.adj != 0] = self.adj[self.adj != 0]
self.mask = nn.Parameter(mask)
else:
self.mask = None
def forward(self, x):
"""
:param x: B, Tin, N, Cin)
:return: B, Tout, N
"""
x = torch.relu(self.First_FC(x)) # B, Tin, N, Cin
for model in self.STSGCLS:
x = model(x, self.mask)
# (B, T - 8, N, Cout)
need_concat = []
for i in range(self.horizon):
out_step = self.predictLayer[i](x) # (B, 1, N)
need_concat.append(out_step)
out = torch.cat(need_concat, dim=1) # B, Tout, N
del need_concat
return out