-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphML.py
4201 lines (3661 loc) · 171 KB
/
graphML.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
graphML.py Module for basic GSP and graph machine learning functions.
Functionals
LSIGF: Applies a linear shift-invariant graph filter
spectralGF: Applies a linear shift-invariant graph filter in spectral form
NVGF: Applies a node-variant graph filter
EVGF: Applies an edge-variant graph filter
jARMA: Applies an ARMA filter using Jacobi iterations
learnAttentionGSO: Computes the GSO following the attention mechanism
graphAttention: Applies a graph attention layer
graphAttentionLSIGF: Applies a LSIGF over the learned graph
graphAttentionEVGF: Applies a EVGF over the learned graph
LSIGF_DB: Applies a delayed linear shift-invariant graph filter for batch GSO
GRNN_DB: Computes the sequence of hidden states for batch GSO
GatedGRNN: Computes the sequence of hidden states for static GSO
Filtering Layers (nn.Module)
GraphFilter: Creates a graph convolutional layer using LSI graph filters
SpectralGF: Creates a graph convolutional layer using LSI graph filters in
spectral form
NodeVariantGF: Creates a graph filtering layer using node-variant graph filters
EdgeVariantGF: Creates a graph filtering layer using edge-variant graph filters
GraphFilterARMA: Creates a (linear) layer that applies a ARMA graph filter
using Jacobi's method
GraphAttentional: Creates a layer using graph attention mechanisms
GraphFilterAttentional: Creates a layer using a graph convolution on a GSO
learned through attention
EdgeVariantAttentional: Creates a layer using an edge variant graph filter
parameterized by several attention mechanisms
GraphFilter_DB: Creates a graph convolutional layer using LSI graph filters
that are applied to a delayed sequence of shift operators
HiddenState_DB: Creates the layer for computing the hidden state of a GRNN
HiddenState: Creates the layer for computing the hidden state of a GRNN (with
static GSO)
TimeGatedHiddenState: Creates the layer for computing the time gated hidden
state of a GRNN
NodeGatedHiddenState: Creates the layer for computing the node gated hidden
state of a GRNN
EdgeGatedHiddenState: Creates the layer for computing the edge gated hidden
state of a GRNN
Activation Functions - Nonlinearities (nn.Module)
MaxLocalActivation: Creates a localized max activation function layer
MedianLocalActivation: Creates a localized median activation function layer
NoActivation: Creates a layer for no activation function
Summarizing Functions - Pooling (nn.Module)
NoPool: No summarizing function.
MaxPoolLocal: Max-summarizing function
"""
import math
import numpy as np
import torch
import torch.nn as nn
import graphTools as graphTools
zeroTolerance = 1e-9 # Values below this number are considered zero.
infiniteNumber = 1e12 # infinity equals this number
# WARNING: Only scalar bias.
#############################################################################
# #
# FUNCTIONALS #
# #
#############################################################################
def LSIGF(h, S, x, b=None):
"""
LSIGF(filter_taps, GSO, input, bias=None) Computes the output of a linear
shift-invariant graph filter on input and then adds bias.
Denote as G the number of input features, F the number of output features,
E the number of edge features, K the number of filter taps, N the number of
nodes, S_{e} in R^{N x N} the GSO for edge feature e, x in R^{G x N} the
input data where x_{g} in R^{N} is the graph signal representing feature
g, and b in R^{F x N} the bias vector, with b_{f} in R^{N} representing the
bias for feature f.
Then, the LSI-GF is computed as
y_{f} = \sum_{e=1}^{E}
\sum_{k=0}^{K-1}
\sum_{g=1}^{G}
[h_{f,g,e}]_{k} S_{e}^{k} x_{g}
+ b_{f}
for f = 1, ..., F.
Inputs:
filter_taps (torch.tensor): array of filter taps; shape:
output_features x edge_features x filter_taps x input_features
GSO (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
input (torch.tensor): input signal; shape:
batch_size x input_features x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
if the same bias is to be applied to all nodes, set number_nodes = 1
so that b_{f} vector becomes b_{f} \mathbf{1}_{N}
Outputs:
output: filtered signals; shape:
batch_size x output_features x number_nodes
"""
# The basic idea of what follows is to start reshaping the input and the
# GSO so the filter coefficients go just as a very plain and simple
# linear operation, so that all the derivatives and stuff on them can be
# easily computed.
# h is output_features x edge_weights x filter_taps x input_features
# S is edge_weighs x number_nodes x number_nodes
# x is batch_size x input_features x number_nodes
# b is output_features x number_nodes
# Output:
# y is batch_size x output_features x number_nodes
# Get the parameter numbers:
F = h.shape[0]
E = h.shape[1]
K = h.shape[2]
G = h.shape[3]
assert S.shape[0] == E
N = S.shape[1]
assert S.shape[2] == N
B = x.shape[0]
assert x.shape[1] == G
assert x.shape[2] == N
# Or, in the notation we've been using:
# h in F x E x K x G
# S in E x N x N
# x in B x G x N
# b in F x N
# y in B x F x N
# Now, we have x in B x G x N and S in E x N x N, and we want to come up
# with matrix multiplication that yields z = x * S with shape
# B x E x K x G x N.
# For this, we first add the corresponding dimensions
x = x.reshape([B, 1, G, N])
S = S.reshape([1, E, N, N])
z = x.reshape([B, 1, 1, G, N]).repeat(1, E, 1, 1, 1) # This is for k = 0
# We need to repeat along the E dimension, because for k=0, S_{e} = I for
# all e, and therefore, the same signal values have to be used along all
# edge feature dimensions.
for k in range(1,K):
x = torch.matmul(x, S) # B x E x G x N
xS = x.reshape([B, E, 1, G, N]) # B x E x 1 x G x N
z = torch.cat((z, xS), dim = 2) # B x E x k x G x N
# This output z is of size B x E x K x G x N
# Now we have the x*S_{e}^{k} product, and we need to multiply with the
# filter taps.
# We multiply z on the left, and h on the right, the output is to be
# B x N x F (the multiplication is not along the N dimension), so we reshape
# z to be B x N x E x K x G and reshape it to B x N x EKG (remember we
# always reshape the last dimensions), and then make h be E x K x G x F and
# reshape it to EKG x F, and then multiply
y = torch.matmul(z.permute(0, 4, 1, 2, 3).reshape([B, N, E*K*G]),
h.reshape([F, E*K*G]).permute(1, 0)).permute(0, 2, 1)
# And permute againt to bring it from B x N x F to B x F x N.
# Finally, add the bias
if b is not None:
y = y + b
return y
def spectralGF(h, V, VH, x, b=None):
"""
spectralGF(filter_coeff, eigenbasis, eigenbasis_hermitian, input, bias=None)
Computes the output of a linear shift-invariant graph filter in spectral
form applying filter_coefficients on the graph fourier transform of the
input .
Denote as G the number of input features, F the number of output features,
E the number of edge features, N the number of nodes, S_{e} in R^{N x N}
the GSO for edge feature e with S_{e} = V_{e} Lambda_{e} V_{e}^{H} as
eigendecomposition, x in R^{G x N} the input data where x_{g} in R^{N} is
the graph signal representing feature g, and b in R^{F x N} the bias vector,
with b_{f} in R^{N} representing the bias for feature f.
Then, the LSI-GF in spectral form is computed as
y_{f} = \sum_{e=1}^{E}
\sum_{g=1}^{G}
V_{e} diag(h_{f,g,e}) V_{e}^{H} x_{g}
+ b_{f}
for f = 1, ..., F, with h_{f,g,e} in R^{N} the filter coefficients for
output feature f, input feature g and edge feature e.
Inputs:
filter_coeff (torch.tensor): array of filter coefficients; shape:
output_features x edge_features x input_features x number_nodes
eigenbasis (torch.tensor): eigenbasis of the graph shift operator;shape:
edge_features x number_nodes x number_nodes
eigenbasis_hermitian (torch.tensor): hermitian of the eigenbasis; shape:
edge_features x number_nodes x number_nodes
input (torch.tensor): input signal; shape:
batch_size x input_features x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
if the same bias is to be applied to all nodes, set number_nodes = 1
so that b_{f} vector becomes b_{f} \mathbf{1}_{N}
Outputs:
output: filtered signals; shape:
batch_size x output_features x number_nodes
Obs.: While we consider most GSOs to be normal (so that the eigenbasis is
an orthonormal basis), this function would also work if V^{-1} is used as
input instead of V^{H}
"""
# The decision to input both V and V_H is to avoid any time spent in
# permuting/inverting the matrix. Because this depends on the graph and not
# the data, it can be done faster if we just input it.
# h is output_features x edge_weights x input_features x number_nodes
# V is edge_weighs x number_nodes x number_nodes
# VH is edge_weighs x number_nodes x number_nodes
# x is batch_size x input_features x number_nodes
# b is output_features x number_nodes
# Output:
# y is batch_size x output_features x number_nodes
# Get the parameter numbers:
F = h.shape[0]
E = h.shape[1]
G = h.shape[2]
N = h.shape[3]
assert V.shape[0] == VH.shape[0] == E
assert V.shape[1] == VH.shape[1] == V.shape[2] == VH.shape[2] == N
B = x.shape[0]
assert x.shape[1] == G
assert x.shape[2] == N
# Or, in the notation I've been using:
# h in F x E x G x N
# V in E x N x N
# VH in E x N x N
# x in B x G x N
# b in F x N
# y in B x F x N
# We will do proper matrix multiplication in this case (algebraic
# multiplication using column vectors instead of CS notation using row
# vectors).
# We will multiply separate VH with x, and V with diag(h).
# First, to multiply VH with x, we need to add one dimension for each one
# of them (dimension E for x and dimension B for VH)
x = x.reshape([B, 1, G, N]).permute(0, 1, 3, 2) # B x 1 x N x G
VH = VH.reshape([1, E, N, N]) # 1 x E x N x N
# Now we multiply. Note that we also permute to make it B x E x G x N
# instead of B x E x N x G because we want to multiply for a specific e and
# g, there we do not want to sum (yet) over G.
VHx = torch.matmul(VH, x).permute(0, 1, 3, 2) # B x E x G x N
# Now we want to multiply V * diag(h), both are matrices. So first, we
# add the necessary dimensions (B and G for V and an extra N for h to make
# it a matrix from a vector)
V = V.reshape([1, E, 1, N, N]) # 1 x E x 1 x N x N
# We note that multiplying by a diagonal matrix to the right is equivalent
# to an elementwise multiplication in which each column is multiplied by
# a different number, so we will do this to make it faster (elementwise
# multiplication is faster than matrix multiplication). We need to repeat
# the vector we have columnwise.
diagh = h.reshape([F, E, G, 1, N]).repeat(1, 1, 1, N, 1) # F x E x G x N x N
# And now we do elementwise multiplication
Vdiagh = V * diagh # F x E x G x N x N
# Finally, we make the multiplication of these two matrices. First, we add
# the corresponding dimensions
Vdiagh = Vdiagh.reshape([1, F, E, G, N, N]) # 1 x F x E x G x N x N
VHx = VHx.reshape([B, 1, E, G, N, 1]) # B x 1 x E x G x N x 1
# And do matrix multiplication to get all the corresponding B,F,E,G vectors
VdiaghVHx = torch.matmul(Vdiagh, VHx) # B x F x E x G x N x 1
# Get rid of the last dimension which we do not need anymore
y = VdiaghVHx.squeeze(5) # B x F x E x G x N
# Sum over G
y = torch.sum(y, dim = 3) # B x F x E x N
# Sum over E
y = torch.sum(y, dim = 2) # B x F x N
# Finally, add the bias
if b is not None:
y = y + b
return y
def NVGF(h, S, x, b=None):
"""
NVGF(filter_taps, GSO, input, bias=None) Computes the output of a
node-variant graph filter on input and then adds bias.
Denote as G the number of input features, F the number of output features,
E the number of edge features, K the number of shifts, N the number of
nodes, S_{e} in R^{N x N} the GSO for edge feature e, x in R^{G x N} the
input data where x_{g} in R^{N} is the graph signal representing feature
g, and b in R^{F x N} the bias vector, with b_{f} in R^{N} representing the
bias for feature f. Denote as h_{k}^{efg} in R^{N} the vector with the N
filter taps corresponding to the efg filter for shift k.
Then, the NV-GF is computed as
y_{f} = \sum_{e=1}^{E}
\sum_{k=0}^{K-1}
\sum_{g=1}^{G}
diag(h_{k}^{efg}) S_{e}^{k} x_{g}
+ b_{f}
for f = 1, ..., F.
Inputs:
filter_taps (torch.tensor): array of filter taps; shape:
output_features x edge_features x filter_taps x input_features
x number_nodes
GSO (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
input (torch.tensor): input signal; shape:
batch_size x input_features x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
if the same bias is to be applied to all nodes, set number_nodes = 1
so that b_{f} vector becomes b_{f} \mathbf{1}_{N}
Outputs:
output: filtered signals; shape:
batch_size x output_features x number_nodes
"""
# h is output_features x edge_weights x filter_taps x input_features
# x number_nodes
# S is edge_weighs x number_nodes x number_nodes
# x is batch_size x input_features x number_nodes
# b is output_features x number_nodes
# Output:
# y is batch_size x output_features x number_nodes
# Get the parameter numbers:
F = h.shape[0]
E = h.shape[1]
K = h.shape[2]
G = h.shape[3]
N = h.shape[4]
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
B = x.shape[0]
assert x.shape[1] == G
assert x.shape[2] == N
# Or, in the notation I've been using:
# h in F x E x K x G x N
# S in E x N x N
# x in B x G x N
# b in F x N
# y in B x F x N
# Now, we have x in B x G x N and S in E x N x N, and we want to come up
# with matrix multiplication that yields z = x * S with shape
# B x E x K x G x N.
# For this, we first add the corresponding dimensions
xr = x.reshape([B, 1, G, N])
Sr = S.reshape([1, E, N, N])
z = xr.reshape([B, 1, 1, G, N]).repeat(1, E, 1, 1, 1) # This is for k = 0
# We need to repeat along the E dimension, because for k=0, S_{e} = I for
# all e, and therefore, the same signal values have to be used along all
# edge feature dimensions.
for k in range(1,K):
xr = torch.matmul(xr, Sr) # B x E x G x N
xS = xr.reshape([B, E, 1, G, N]) # B x E x 1 x G x N
z = torch.cat((z, xS), dim = 2) # B x E x k x G x N
# This output z is of size B x E x K x G x N
# Now we have the x*S_{e}^{k} product, and we need to multiply with the
# filter taps.
# This multiplication with filter taps is ``element wise'' on N since for
# each node we have a different element
# First, add the extra dimension (F for z, and B for h)
z = z.reshape([B, 1, E, K, G, N])
h = h.reshape([1, F, E, K, G, N])
# Now let's do elementwise multiplication
zh = z * h
# And sum over the dimensions E, K, G to get B x F x N
y = torch.sum(zh, dim = 4) # Sum over G
y = torch.sum(y, dim = 3) # Sum over K
y = torch.sum(y, dim = 2) # Sum over E
# Finally, add the bias
if b is not None:
y = y + b
return y
def EVGF(S, x, b=None):
"""
EVGF(filter_matrices, input, bias=None) Computes the output of an
edge-variant graph filter on input and then adds bias.
Denote as G the number of input features, F the number of output features,
E the number of edge features, K the number of shifts, N the number of
nodes, Phi_{efg} in R^{N x N} the filter matrix for edge feature e, output
feature f and input feature g (recall that Phi_{efg}^{k} has the same
sparsity pattern as the graph, except for Phi_{efg}^{0} which is expected to
be a diagonal matrix), x in R^{G x N} the input data where x_{g} in R^{N} is
the graph signal representing feature g, and b in R^{F x N} the bias vector,
with b_{f} in R^{N} representing the bias for feature f.
Then, the EV-GF is computed as
y_{f} = \sum_{e=1}^{E}
\sum_{k=0}^{K-1}
\sum_{g=1}^{G}
Phi_{efg}^{k:0} x_{g}
+ b_{f}
for f = 1, ..., F, with Phi_{efg}^{k:0} = Phi_{efg}^{k} Phi_{efg}^{k-1} ...
Phi_{efg}^{0}.
Inputs:
filter_matrices (torch.tensor): array of filter matrices; shape:
output_features x edge_features x filter_taps x input_features
x number_nodes x number_nodes
input (torch.tensor): input signal; shape:
batch_size x input_features x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
if the same bias is to be applied to all nodes, set number_nodes = 1
so that b_{f} vector becomes b_{f} \mathbf{1}_{N}
Outputs:
output: filtered signals; shape:
batch_size x output_features x number_nodes
"""
# We just need to multiply by the filter_matrix recursively, and then
# add for all E, G, and K features.
# S is output_features x edge_features x filter_taps x input_features
# x number_nodes x number_nodes
# x is batch_size x input_features x number_nodes
# b is output_features x number_nodes
# Output:
# y is batch_size x output_features x number_nodes
# Get the parameter numbers:
F = S.shape[0]
E = S.shape[1]
K = S.shape[2]
G = S.shape[3]
N = S.shape[4]
assert S.shape[5] == N
B = x.shape[0]
assert x.shape[1] == G
assert x.shape[2] == N
# Or, in the notation I've been using:
# S in F x E x K x G x N x N
# x in B x G x N
# b in F x N
# y in B x F x N
# We will be doing matrix multiplications in the algebraic way, trying to
# multiply the N x N matrix corresponding to the appropriate e, f, k and g
# dimensions, with the respective x vector (N x 1 column vector)
# For this, we first add the corresponding dimensions (for x we add
# dimensions F, E and the last dimension for column vector)
x = x.reshape([B, 1, 1, G, N, 1])
# When we do index_select along dimension K we get rid of this dimension
Sk = torch.index_select(S, 2, torch.tensor(0).to(S.device)).squeeze(2)
# Sk in F x E x G x N x N
# And we add one further dimension for the batch size B
Sk = Sk.unsqueeze(0) # 1 x F x E x G x N x N
# Matrix multiplication
x = torch.matmul(Sk, x) # B x F x E x G x N x 1
# And we collect this for every k in a vector z, along the K dimension
z = x.reshape([B, F, E, 1, G, N, 1]).squeeze(6) # B x F x E x 1 x G x N
# Now we do all the matrix multiplication
for k in range(1,K):
# Extract the following k
Sk = torch.index_select(S, 2, torch.tensor(k).to(S.device)).squeeze(2)
# Sk in F x E x G x N x N
# Give space for the batch dimension B
Sk = Sk.unsqueeze(0) # 1 x F x E x G x N x N
# Multiply with the previously cumulative Sk * x
x = torch.matmul(Sk, x) # B x F x E x G x N x 1
# Get rid of the last dimension (of a column vector)
Sx = x.reshape([B, F, E, 1, G, N, 1]).squeeze(6) # B x F x E x 1 x G x N
# Add to the z
z = torch.cat((z, Sx), dim = 2) # B x F x E x k x G x N
# Sum over G
z = torch.sum(z, dim = 4)
# Sum over K
z = torch.sum(z, dim = 3)
# Sum over E
y = torch.sum(z, dim = 2)
if b is not None:
y = y + b
return y
def jARMA(psi, varphi, phi, S, x, b=None, tMax = 5):
"""
jARMA(inverse_taps, direct_taps, filter_taps, GSO, input, bias = None,
tMax = 5) Computes the output of an ARMA filter using Jacobi
iterations.
The output of an ARMA computed by means of tMax Jacobi iterations is given
as follows
y^{f} = \sum_{e=1}^{E} \sum_{g=1}^{G}
\sum_{p=0}^{P-1}
H_{p}^{1}(S) (\bar{S}_{p}^{fge})^{-1} x
+ H_{p}^{2}(S) x
+ H^{3}(S) x
where E is the total number of edge features, G is the total number of input
features, and P is the order of the denominator polynomial. The filters are
H_{p}^{1}(S)
= \sum_{tau=0}^{t}
(-1)^{tau} varphi_{p}^{fge} (\barS_{p}^{-1} \tilde{S})^{tau}
H_{p}^{2}(S)
= (-1)^{t+1} ((\bar{S}_{p}^{fge})^{-1} \tilde{S})^{t+1}
H^{2}(S) = \sum_{k=0}^{K-1} phi_{k}^{fge} S^{k}
where varphi_{p}^{fge} are the direct filter taps of the rational one ARMA
filter, phi_{k}^{fge} are the filter taps of the residue LSIGF filter, and
the GSOs used derive from GSO S and are
\bar{S}_{p}^{fge} = Diag(S) - psi_{p}^{fge} I_{N}
\tilde{S} = DiagOff(S)
with psi_{p}^{fge} the inverse filter taps of the rational one ARMA filter.
Inputs:
inverse_taps (torch.tensor): array of filter taps psi_{p}^{fge}; shape:
out_features x edge_features x denominator_order x in_features
direct_taps (torch.tensor): array of taps varphi_{p}^{fge}; shape:
out_features x edge_features x denominator_order x in_features
filter_taps (torch.tensor): array of filter taps phi_{p}^{fge}; shape:
out_features x edge_features x residue_order x in_features
GSO (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
input (torch.tensor): input signal; shape:
batch_size x input_features x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
if the same bias is to be applied to all nodes, set number_nodes = 1
so that b_{f} vector becomes b_{f} \mathbf{1}_{N} (default: None)
tMax (int): value of t for computing the Jacobi approximation
(default: 5)
Outputs:
output: filtered signals; shape:
batch_size x output_features x number_nodes
"""
# The inputs are:
# psi in F x E x P x G (inverse coefficient in order-one rational)
# varphi in F x E x P x G (direct coefficient in order-one rational)
# phi in F x E x K x G (direct filter coefficients)
# x in B x G x N
# S in E x N x N
F = psi.shape[0] # out_features
E = psi.shape[1] # edge_features
P = psi.shape[2] # inverse polynomial order
G = psi.shape[3] # in_features
assert varphi.shape[0] == F
assert varphi.shape[1] == E
assert varphi.shape[2] == P
assert varphi.shape[3] == G
assert phi.shape[0] == F
assert phi.shape[1] == E
assert phi.shape[3] == G
B = x.shape[0] # batch_size
assert x.shape[1] == G
N = x.shape[2] # number_nodes
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
# First, let's build Stilde and Sbar
Stilde = torch.empty(0).to(S.device) # Will be of shape E x N x N
DiagS = torch.empty(0).to(S.device) # Will be of shape E x N x N
for e in range(E):
thisS = torch.index_select(S,0,torch.tensor(e).to(S.device)).squeeze(0)
thisDiagS = torch.diag(torch.diag(thisS))
DiagOffS = (thisS - thisDiagS).unsqueeze(0) # E x N x N
Stilde = torch.cat((Stilde, DiagOffS), dim = 0)
DiagS = torch.cat((DiagS, thisDiagS.unsqueeze(0)), dim = 0)
I = torch.eye(N).reshape([1, 1, 1, 1, N, N]).to(S.device) # (FxExPxGxNxN)
psiI = psi.reshape([F, E, P, G, 1, 1]) * I
DiagS = DiagS.reshape([1, E, 1, 1, N, N])
Sbar = DiagS - psiI # F x E x P x G x N x N
# Now, invert Sbar, that doesn't depend on t either, and multiply it by x
# Obs.: We cannot just do 1/Sbar, because all the nonzero elements will
# give inf, ruining everything. So we will force the off-diagonal elements
# to be one, and then get rid of them
offDiagonalOnes = (torch.ones(N,N) - torch.eye(N)).to(Sbar.device)
SbarInv = 1/(Sbar + offDiagonalOnes) # F x E x P x G x N x N
SbarInv = SbarInv * torch.eye(N).to(Sbar.device)
SbarInvX = torch.matmul(SbarInv.reshape([1, F, E, P, G, N, N]),
x.reshape([B, 1, 1, 1, G, N, 1])).squeeze(6)
# B x F x E x P x G x N
# And also multiply SbarInv with Stilde which is also used in H1 and H2
SbarInvStilde = torch.matmul(SbarInv,
Stilde.reshape([1, E, 1, 1, N, N]))
# B x F x E x P x G x N x N
# Next, filtering through H^{3}(S) also doesn't depend on t or p, so
H3x = LSIGF(phi, S, x)
# Last, build the output from combining all filters H1, H2 and H3
# Compute H1 SbarInvX
z = SbarInvX.reshape([B, F, E, 1, P, G, N])
y = x.reshape([B, 1, 1, 1, G, N, 1]) # (B x F x E x P x G x N x 1)
x1 = SbarInvX.unsqueeze(6) # B x F x E x P x G x N x 1
# (B x F x E x tau x P x G x N)
for tau in range(1,tMax+1):
x1 = torch.matmul(SbarInvStilde.unsqueeze(0),# 1 x F x E x P x G x N x N
x1)
# B x F x E x P x G x N x 1
z = torch.cat((z, x1.squeeze(6).unsqueeze(3)), dim = 3)
# B x F x E x tau x P x G x N
y = torch.matmul(SbarInvStilde.unsqueeze(0), # 1 x F x E x P x G x N x N
y)
# B x F x E x P x G x N x 1
thisCoeffs = torch.tensor((-1.) ** np.arange(0,tMax+1)).to(x.device)
thisCoeffs = thisCoeffs.reshape([1, 1, 1, tMax+1, 1, 1]) * \
varphi.reshape([1, F, E, 1, P, G])\
.repeat(1, 1, 1, tMax+1, 1, 1)
# 1 x F x E x (tMax+1) x P x G
thisCoeffs = thisCoeffs.permute(0, 4, 1, 2, 3, 5)
# 1 x P x F x E x (tMax+1) x G
z = z.permute(0, 4, 1, 6, 2, 3, 5) # B x P x F x N x E x (tMax+1) x G
thisCoeffs = thisCoeffs.reshape([1, P, F, E*(tMax+1)*G]).unsqueeze(4)
# 1 x P x F x E(tMax+1)G x 1
z = z.reshape(B, P, F, N, E*(tMax+1)*G)
# B x P x F x N x E*(tMax+1)*G
H1x = torch.matmul(z, thisCoeffs).squeeze(4)
# B x P x F x N
# Now, to compute H2x we need y, but y went only up to value tMax, and
# we need to go to tMax+1, so we need to multiply it once more
y = torch.matmul(SbarInvStilde.unsqueeze(0), y).squeeze(6)
# B x F x E x P x G x N
H2x = -y if np.mod(tMax,2) == 0 else y
H2x = torch.sum(H2x, dim = 4) # sum over G, shape: B x F x E x P x N
H2x = torch.sum(H2x, dim = 2) # sume over E, shape: B x F x P x N
H2x = H2x.permute(0, 2, 1, 3) # B x P x F x N
# Finally, we add up H1x and H2x and sum over all p, and add to H3 to
# update u
u = torch.sum(H1x + H2x, dim = 1) + H3x
if b is not None:
u = u+b
return u
def learnAttentionGSO(x, a, W, S, negative_slope=0.2):
"""
learnAttentionGSO(x, a, W, S) Computes the GSO following the attention
mechanism
Denote as G the number of input features, F the number of output features,
E the number of edge features, P the number of attention heads, Ji the
number of nodes in N_{i}, the neighborhood of node i, and N the number of
nodes. Let x_{i} in R^{G} be the feature associated to node i,
W^{ep} in R^{F x G} the weight marix associated to edge feature e and
attention head p, and a^{ep} in R^{2F} the mixing vector. Let
alpha_{ij}^{ep} in R the attention coefficient between nodes i and j, for
edge feature e and attention head p, and let s_{ij}^{e} be the value of
feature e of the edge connecting nodes i and j.
Each elements of the new GSO is alpha_{ij}^{ep} computed as
alpha_{ij}^{ep} = softmax_{j} ( LeakyReLU_{beta} (
(a^{ep})^T [cat(W^{ep}x_{i}, W^{ep} x_{j})]
))
for all j in N_{i}, and where beta is the negative slope of the leaky ReLU.
Inputs:
x (torch.tensor): input;
shape: batch_size x input_features x number_nodes
a (torch.tensor): mixing parameter; shape:
number_heads x edge_features x 2 * output_features
W (torch.tensor): linear parameter; shape:
number_heads x edge_features x output_features x input_features
S (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
negative_slope (float): negative slope of the leaky relu (default: 0.2)
Outputs:
aij: output GSO; shape:
batch_size x number_heads x edge_features x number_nodes x number_nodes
"""
B = x.shape[0] # batch_size
G = x.shape[1] # input_features
N = x.shape[2] # number_nodes
P = a.shape[0] # number_heads
E = a.shape[1] # edge_features
assert W.shape[0] == P
assert W.shape[1] == E
F = W.shape[2] # output_features
assert a.shape[2] == int(2*F)
G = W.shape[3] # input_features
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
# Add ones of the GSO at all edge feature levels so that the node always
# has access to itself. The fact that it's one is not so relevant, because
# the attention coefficient that is learned would compensate for this
S = S + torch.eye(N).reshape([1,N,N]).repeat(E,1,1).to(S.device)
# WARNING:
# (If the GSOs already have self-connections, then these will be added a 1,
# which might be a problem if the self-connection is a -1. I will have to
# think of this more carefully)
# W is of size P x E x F x G
# a is of size P x E x 2F
# Compute Wx for all nodes
x = x.reshape([B, 1, 1, G, N])
W = W.reshape([1, P, E, F, G])
Wx = torch.matmul(W, x) # B x P x E x F x N
# Now, do a_1^T Wx, and a_2^T Wx to get a tensor of shape B x P x E x 1 x N
# because we're applying the inner product on the F dimension.
a1 = torch.index_select(a, 2, torch.arange(F).to(x.device)) # K x E x F
a2 = torch.index_select(a, 2, torch.arange(F, 2*F).to(x.device)) # K x E x F
a1Wx = torch.matmul(a1.reshape([1, P, E, 1, F]), Wx) # B x P x E x 1 x N
a2Wx = torch.matmul(a2.reshape([1, P, E, 1, F]), Wx) # B x P x E x 1 x N
# And then, use this to sum them accordingly and create a B x P x E x N x N
# matrix.
aWx = a1Wx + a2Wx.permute(0, 1, 2, 4, 3) # B x P x E x N x N
# Obs.: In this case, we have one column vector and one row vector; then,
# what the sum does, is to repeat the column and the row, respectively,
# until both matrices are of the same size, and then adds up, which is
# precisely what we want to do
# Apply the LeakyRelu
eij = nn.functional.leaky_relu(aWx, negative_slope = negative_slope)
# B x P x E x N x N
# Each element of this N x N matrix is, precisely, e_ij (eq. 1) in the GAT
# paper.
# And apply the softmax. For the softmax, we do not want to consider
# the places where there are no neighbors, so we need to set them to -infty
# so that they will be assigned a zero.
# First, get places where we have edges
maskEdges = torch.sum(torch.abs(S.data), dim = 0)
# Make it a binary matrix
maskEdges = (maskEdges > zeroTolerance).type(x.dtype)
# Make it -infinity where there are zeros
infinityMask = (1-maskEdges) * infiniteNumber
# Compute the softmax plus the -infinity (we first force the places where
# there is no edge to be zero, and then we add -infinity to them)
aij = nn.functional.softmax(eij*maskEdges - infinityMask, dim = 4)
# B x P x E x N x N
# This will give me a matrix of all the alpha_ij coefficients.
# Re-inforce the zeros just to be sure
return aij * maskEdges # B x P x E x N x N
def graphAttention(x, a, W, S, negative_slope=0.2):
"""
graphAttention(x, a, W, S) Computes attention following GAT layer taking
into account multiple edge features.
Denote as G the number of input features, F the number of output features,
E the number of edge features, P the number of attention heads, Ji the
number of nodes in N_{i}, the neighborhood of node i, and N the number of
nodes. Let x_{i} in R^{G} be the feature associated to node i,
W^{ep} in R^{F x G} the weight marix associated to edge feature e and
attention head p, and a^{ep} in R^{2F} the mixing vector. Let
alpha_{ij}^{ep} in R the attention coefficient between nodes i and j, for
edge feature e and attention head p, and let s_{ij}^{e} be the value of
feature e of the edge connecting nodes i and j.
Let y_{i}^{p} in R^{F} be the output of the graph attention at node i for
attention head p. It is computed as
y_{i}^{p} = \sum_{e=1}^{E}
\sum_{j in N_{i}}
s_{ij}^{e} alpha_{ij}^{ep} W^{ep} x_{j}
with
alpha_{ij}^{ep} = softmax_{j} ( LeakyReLU_{beta} (
(a^{ep})^T [cat(W^{ep}x_{i}, W^{ep} x_{j})]
))
for all j in N_{i}, and where beta is the negative slope of the leaky ReLU.
Inputs:
x (torch.tensor): input;
shape: batch_size x input_features x number_nodes
a (torch.tensor): mixing parameter; shape:
number_heads x edge_features x 2 * output_features
W (torch.tensor): linear parameter; shape:
number_heads x edge_features x output_features x input_features
S (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
negative_slope (float): negative slope of the leaky relu (default: 0.2)
Outputs:
y: output; shape:
batch_size x number_heads x output_features x number_nodes
"""
B = x.shape[0] # batch_size
G = x.shape[1] # input_features
N = x.shape[2] # number_nodes
P = a.shape[0] # number_heads
E = a.shape[1] # edge_features
assert W.shape[0] == P
assert W.shape[1] == E
F = W.shape[2] # output_features
assert a.shape[2] == int(2*F)
G = W.shape[3] # input_features
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
# First, we need to learn the attention GSO
aij = learnAttentionGSO(x, a, W, S, negative_slope = negative_slope)
# B x P x E x N x N
# Then, we need to compute the high-level features
# W is of size P x E x F x G
# a is of size P x E x 2F
# Compute Wx for all nodes
x = x.reshape([B, 1, 1, G, N])
W = W.reshape([1, P, E, F, G])
Wx = torch.matmul(W, x) # B x P x E x F x N
# Finally, we just need to apply this matrix to the Wx which we have already
# computed, and done.
y = torch.matmul(Wx, S.reshape([1, 1, E, N, N]) * aij) # B x P x E x F x N
# And sum over all edges
return torch.sum(y, dim = 2) # B x P x F x N
def graphAttentionLSIGF(h, x, a, W, S, b=None, negative_slope=0.2):
"""
graphAttentionLSIGF(h, x, a, W, S) Computes a graph convolution
(LSIGF) over a graph shift operator learned through the attention
mechanism
Inputs:
h (torch.tensor): array of filter taps; shape:
edge_features x filter_taps
x (torch.tensor): input; shape:
batch_size x input_features x number_nodes
a (torch.tensor): mixing parameter; shape:
number_heads x edge_features x 2 * out_features
W (torch.tensor): linear parameter; shape:
number_heads x edge_features x out_features x input_features
S (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
negative_slope (float): negative slope of the leaky relu (default: 0.2)
Outputs:
y: output; shape:
batch_size x number_heads x output_features x number_nodes
"""
E = h.shape[0] # edge_features
K = h.shape[1] # filter_taps
B = x.shape[0] # batch_size
G = x.shape[1] # input_features
N = x.shape[2] # number_nodes
P = a.shape[0] # number_heads
E = a.shape[1] # edge_features
assert W.shape[0] == P
assert W.shape[1] == E
F = W.shape[2] # out_features
assert W.shape[3] == G
assert a.shape[2] == int(2*F)
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
# First, we need to learn the attention GSO
aij = learnAttentionGSO(x, a, W, S, negative_slope = negative_slope)
# B x P x E x N x N
# And now we need to compute an LSIGF with this learned GSO, but the filter
# taps of the LSIGF are a combination of h (along K), and W (along F and G)
# So, we have
# h in E x K
# W in P x E x G x F
# The filter taps, will thus have shape
# h in P x F x E x K x G
h = h.reshape([1, 1, E, K, 1]) # (P x F x E x K x G)
W = W.permute(0, 3, 1, 2) # P x F x E x G
W = W.reshape([P, F, E, 1, G]) # (P x F x E x K x G)
h = h * W # P x F x E x K x G (We hope, if not, we need to repeat on the
# corresponding dimensions)
x = x.reshape([B, 1, 1, G, N]) # (B x P x E x G x N)
# The easiest would be to use the LSIGF function, but that takes as input
# a B x F x N input, and while we could join together B and P into a single
# dimension, we would still be unable to handle the E features this way.
# So we basically need to copy the code from LSIGF but accounting the
# matrix multiplications with multiple edge features as Wx has
z = x.reshape([B, 1, 1, 1, G, N]).repeat(1, P, E, 1, 1, 1)
# add the k=0 dimension (B x P x E x K x G x N)
# And now do the repeated multiplication with S
for k in range(1,K):
x = torch.matmul(x, aij) # B x P x E x G x N
xAij = x.reshape([B, P, E, 1, G, N]) # add the k dimension
z = torch.cat((z, xAij), dim = 3) # B x P x E x k x G x N
# This output z is of shape B x P x E x K x M x N and represents the product
# x * aij_{e}^{k} (i.e. the multiplication between x and the kth power of
# the learned GSO).
# Now, we need to multiply this by the filter coefficients
# Convert h, from F x E x K x M to EKM x F to multiply from the right
h = h.reshape([1, P, F, E*K*G]) # (B x P x F x (EKG))
h = h.permute(0, 1, 3, 2) # (B x P x EKG x F)
# And z from B x P x E x K x G x N to B x P x N x EKG to left multiply
z = z.permute(0, 1, 5, 2, 3, 4).reshape([B, P, N, E*K*G])
# And multiply
y = torch.matmul(z, h) # B x P x N x F
y = y.permute(0, 1, 3, 2) # The output needs to be B x P x F x N
# Finally, add the bias
if b is not None:
y = y+b
return y
def graphAttentionEVGF(x, a, W, S, b=None, negative_slope=0.2):
"""
graphAttentionEVGF(h, x, a, W, S) Computes an edge varying graph filter
(EVGF) where each EVGF is learned by an attention mechanism
Inputs:
x (torch.tensor): input; shape:
batch_size x input_features x number_nodes
a (torch.tensor): mixing parameter; shape:
number_heads x filter_taps x edge_features x 2 * out_features
W (torch.tensor): linear parameter; shape:
number_heads x filter_taps x edge_features x out_features x input_features
S (torch.tensor): graph shift operator; shape:
edge_features x number_nodes x number_nodes
bias (torch.tensor): shape: output_features x number_nodes
negative_slope (float): negative slope of the leaky relu (default: 0.2)
Outputs:
y: output; shape:
batch_size x number_heads x output_features x number_nodes
"""
B = x.shape[0] # batch_size
G = x.shape[1] # input_features
N = x.shape[2] # number_nodes
P = a.shape[0] # number_heads
K = a.shape[1] # filter_taps
E = a.shape[2] # edge_features
assert W.shape[0] == P
assert W.shape[1] == K
assert W.shape[2] == E
F = W.shape[3] # output_features
assert W.shape[4] == G
assert a.shape[3] == int(2*F)
assert S.shape[0] == E
assert S.shape[1] == S.shape[2] == N
# First, we need to compute the high-level features
# W is of size P x K x E x F x G
# a is of size P x K x E x 2F
# To compute Wx, we need the first element (K = 0)
W0 = torch.index_select(W, 1, torch.tensor(0).to(S.device)).squeeze(1)
# P x E x F x G
W0 = W0.reshape([1, P, E, F, G])
W0x = torch.matmul(W0, x.reshape([B, 1, 1, G, N])) # B x P x E x F x N
# Now we proceed to learn the rest of the EVGF.
# That first filter coefficient (for the one-hop neighborhood) is learned
# from the first element along the K dimension (dim = 1)
thisa = torch.index_select(a, 1, torch.tensor(0).to(S.device)).squeeze(1)
thisW = torch.index_select(W, 1, torch.tensor(0).to(S.device)).squeeze(1)
aij = learnAttentionGSO(x, thisa, thisW, S, negative_slope = negative_slope)
# B x P x E x N x N (repesents k=0,1)
W0x = torch.matmul(W0x, S.reshape([1, 1, E, N, N]) * aij) # B x P x E x F x N
y = W0x # This is the first multiplication between Wx and Aij corresponding
# to the first-hop neighborhood
# Now, we move on to the rest of the coefficients
for k in range(1, K):
thisa = torch.index_select(a,1, torch.tensor(k).to(S.device)).squeeze(1)
thisW = torch.index_select(W,1, torch.tensor(k).to(S.device)).squeeze(1)
aij = learnAttentionGSO(x, thisa, thisW, S,
negative_slope = negative_slope)
W0x = torch.matmul(W0x, S.reshape([1, 1, E, N, N]) * aij)
# This multiplies the previous W0x Aij^{1:k-1} with A_ij^{(k)}
y = y + W0x # Adds that multiplication to the running sum for all other
# ks, shape: B x P x E x F x N
# Sum over all edge features
y = torch.sum(y, dim = 2) # B x P x F x N
# Finally, add the bias
if b is not None:
y = y+b
return y
#############################################################################
# #
# FUNCTIONALS (Batch, and time-varying) #
# #
#############################################################################
def LSIGF_DB(h, S, x, b=None):
"""
LSIGF_DB(filter_taps, GSO, input, bias=None) Computes the output of a
linear shift-invariant graph filter (graph convolution) on delayed
input and then adds bias.
Denote as G the number of input features, F the number of output features,
E the number of edge features, K the number of filter taps, N the number of
nodes, S_{e}(t) in R^{N x N} the GSO for edge feature e at time t,
x(t) in R^{G x N} the input data at time t where x_{g}(t) in R^{N} is the
graph signal representing feature g, and b in R^{F x N} the bias vector,
with b_{f} in R^{N} representing the bias for feature f.
Then, the LSI-GF is computed as
y_{f} = \sum_{e=1}^{E}
\sum_{k=0}^{K-1}
\sum_{g=1}^{G}
[h_{f,g,e}]_{k} S_{e}(t)S_{e}(t-1)...S_{e}(t-(k-1))
x_{g}(t-k)
+ b_{f}
for f = 1, ..., F.
Inputs:
filter_taps (torch.tensor): array of filter taps; shape:
output_features x edge_features x filter_taps x input_features
GSO (torch.tensor): graph shift operator; shape:
batch_size x time_samples x edge_features
x number_nodes x number_nodes