forked from Drizzle-Zhang/SCRIPT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
1342 lines (1132 loc) · 56.6 KB
/
Copy pathmodel.py
File metadata and controls
1342 lines (1132 loc) · 56.6 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
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
# _*_ coding: utf-8 _*_
# @author: Drizzle_Zhang
# @file: model.py
# @time: 2023/2/1 14:30
from time import time
import os
import subprocess
from typing import Optional, Tuple, Union
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor, device
from torch.nn import Module
from torch.optim import Optimizer
from torch_geometric.loader import DataLoader
from torch_geometric.data import Data
from torch_geometric.nn.norm import LayerNorm
from torch_geometric.nn.conv import GraphConv, MessagePassing
# from torch_geometric.nn import GraphConv, BatchNorm, LayerNorm, TransformerConv, GATv2Conv, ChebConv
from torch_geometric.typing import Adj, OptTensor, PairTensor
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.utils import add_self_loops, remove_self_loops, softmax
import scanpy as sc
import numpy as np
import pandas as pd
import anndata as ad
import captum.attr as attr
from audtorch.metrics.functional import pearsonr
from torch_sparse import SparseTensor, set_diag, matmul
from scipy import stats
from sklearn.metrics import silhouette_score, adjusted_rand_score
from sklearn.cluster import KMeans
from tqdm import tqdm
class GATConvW(MessagePassing):
def __init__(
self,
in_channels: Union[int, Tuple[int, int]],
out_channels: int,
heads: int = 1,
concat: bool = True,
negative_slope: float = 0.2,
dropout: float = 0.0,
add_self_loops: bool = True,
edge_dim: Optional[int] = None,
fill_value: Union[float, Tensor, str] = 'mean',
bias: bool = True,
share_weights: bool = False,
**kwargs,
):
super().__init__(node_dim=0, **kwargs)
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.add_self_loops = add_self_loops
self.edge_dim = edge_dim
self.fill_value = fill_value
self.share_weights = share_weights
if isinstance(in_channels, int):
self.lin_l = Linear(in_channels, heads * out_channels, bias=bias,
weight_initializer='glorot')
if share_weights:
self.lin_r = self.lin_l
else:
self.lin_r = Linear(in_channels, heads * out_channels,
bias=bias, weight_initializer='glorot')
else:
self.lin_l = Linear(in_channels[0], heads * out_channels,
bias=bias, weight_initializer='glorot')
if share_weights:
self.lin_r = self.lin_l
else:
self.lin_r = Linear(in_channels[1], heads * out_channels,
bias=bias, weight_initializer='glorot')
self.att = nn.Parameter(torch.Tensor(1, heads, out_channels))
if edge_dim is not None:
self.lin_edge = Linear(edge_dim, heads * out_channels, bias=False,
weight_initializer='glorot')
else:
self.lin_edge = None
if bias and concat:
self.bias = nn.Parameter(torch.Tensor(heads * out_channels))
elif bias and not concat:
self.bias = nn.Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
_alpha: OptTensor
self._alpha = None
self.reset_parameters()
def reset_parameters(self):
self.lin_l.reset_parameters()
self.lin_r.reset_parameters()
if self.lin_edge is not None:
self.lin_edge.reset_parameters()
glorot(self.att)
zeros(self.bias)
def forward(self, x: Union[Tensor, PairTensor], edge_index: Adj,
edge_attr: OptTensor = None, edge_weight: OptTensor = None,
return_attention_weights: bool = None):
H, C = self.heads, self.out_channels
x_l: OptTensor = None
x_r: OptTensor = None
if isinstance(x, Tensor):
assert x.dim() == 2
x_l = self.lin_l(x).view(-1, H, C)
if self.share_weights:
x_r = x_l
else:
x_r = self.lin_r(x).view(-1, H, C)
else:
x_l, x_r = x[0], x[1]
assert x[0].dim() == 2
x_l = self.lin_l(x_l).view(-1, H, C)
if x_r is not None:
x_r = self.lin_r(x_r).view(-1, H, C)
assert x_l is not None
assert x_r is not None
if self.add_self_loops:
if isinstance(edge_index, Tensor):
num_nodes = x_l.size(0)
if x_r is not None:
num_nodes = min(num_nodes, x_r.size(0))
edge_index, edge_attr = remove_self_loops(
edge_index, edge_attr)
edge_index, edge_attr = add_self_loops(
edge_index, edge_attr, fill_value=self.fill_value,
num_nodes=num_nodes)
elif isinstance(edge_index, SparseTensor):
if self.edge_dim is None:
edge_index = set_diag(edge_index)
else:
raise NotImplementedError(
"The usage of 'edge_attr' and 'add_self_loops' "
"simultaneously is currently not yet supported for "
"'edge_index' in a 'SparseTensor' form")
# propagate_type: (x: PairTensor, edge_attr: OptTensor)
out = self.propagate(edge_index, x=(x_l, x_r),
edge_attr=edge_attr, edge_weight=edge_weight, size=None)
alpha = self._alpha
self._alpha = None
if self.concat:
out = out.view(-1, self.heads * self.out_channels)
else:
out = out.mean(dim=1)
if self.bias is not None:
out += self.bias
if isinstance(return_attention_weights, bool):
assert alpha is not None
if isinstance(edge_index, Tensor):
return out, (edge_index, alpha)
elif isinstance(edge_index, SparseTensor):
return out, edge_index.set_value(alpha, layout='coo')
else:
return out
def message(self, x_j: Tensor, x_i: Tensor, edge_attr: OptTensor, edge_weight: OptTensor,
index: Tensor, ptr: OptTensor,
size_i: Optional[int]) -> Tensor:
x = x_i + x_j
if edge_attr is not None:
if edge_attr.dim() == 1:
edge_attr = edge_attr.view(-1, 1)
assert self.lin_edge is not None
edge_attr = self.lin_edge(edge_attr)
edge_attr = edge_attr.view(-1, self.heads, self.out_channels)
x += edge_attr
x = F.leaky_relu(x, self.negative_slope)
alpha = (x * self.att).sum(dim=-1)
alpha = softmax(alpha, index, ptr, size_i)
self._alpha = alpha
alpha = F.dropout(alpha, p=self.dropout, training=self.training)
x_j = x_j * alpha.unsqueeze(-1)
if edge_weight is None:
return x_j
else:
edge_weight = edge_weight.view(-1, 1, 1)
return edge_weight * x_j
def __repr__(self) -> str:
return (f'{self.__class__.__name__}({self.in_channels}, '
f'{self.out_channels}, heads={self.heads})')
class SCReGAT(torch.nn.Module):
def __init__(self, input_channels: int, hidden_channels: int, num_head: int, num_gene: int,
num_celltype: int, num_nodes: int):
super(SCReGAT, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.lin1_x = nn.Linear(input_channels, hidden_channels)
self.lin1_edge = nn.Linear(input_channels, hidden_channels)
self.conv1 = GATConvW(hidden_channels, hidden_channels, heads=num_head, dropout=0.5,
edge_dim=hidden_channels, add_self_loops=False)
self.ln_1 = LayerNorm(self.num_nodes)
self.lin2 = nn.Linear(1, hidden_channels)
self.conv2 = GATConvW(hidden_channels, hidden_channels,
heads=1, dropout=0.5, add_self_loops=False)
self.ln_2 = LayerNorm(num_gene)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x: Tensor, edge_index: Tensor, edge_tf: Tensor, batch: Tensor,
edge_weight: Optional[Tensor] = None, edge_weight_tf: Optional[Tensor] = None):
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x).sigmoid()
x_edge = self.lin1_edge(x_edge).sigmoid()
x, atten_w = self.conv1(x, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = torch.mean(x, dim=-1, keepdim=False)
# x_1 = self.ln_1(x)
x_1 = x
x = x_1.unsqueeze(-1).view(batchsize*self.num_nodes, -1)
x = self.lin2(x).sigmoid()
x, atten_w2 = self.conv2(x, edge_tf, edge_attr=None, edge_weight=edge_weight_tf,
return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = torch.mean(x, dim=-1, keepdim=False)
x_2 = x_1 + x
x_gene = x_2[:, :self.num_gene]
x_gene = self.ln_2(x_gene)
x_label = self.lin3(x_gene).relu()
x_label = F.dropout(x_label, p=0.5, training=self.training)
x_label = self.lin4(x_label)
return F.log_softmax(x_label, dim=1), F.log_softmax(x_gene, dim=1), atten_w, atten_w2
class GCN(torch.nn.Module):
def __init__(self, input_channels, hidden_channels, num_gene, num_nodes):
super(GCN, self).__init__()
self.num_nodes = num_nodes
self.num_gene = num_gene
torch.manual_seed(12345)
self.conv1 = GraphConv(input_channels, hidden_channels)
self.conv2 = GraphConv(hidden_channels, hidden_channels)
self.ln = LayerNorm(num_gene)
def forward(self, x, edge_index, batch, edge_weight=None):
batchsize = len(torch.unique(batch))
x = self.conv1(x, edge_index, edge_weight).relu()
x = self.conv2(x, edge_index, edge_weight)
x = torch.mean(x, dim=1, keepdim=True)
x = x.view(batchsize, x.shape[0]//batchsize)
x_1 = x[:, :self.num_gene]
x_1 = self.ln(x_1)
return F.log_softmax(x_1, dim=1)
class GAT(torch.nn.Module):
def __init__(self, input_channels, hidden_channels, num_head, num_gene, num_nodes):
super(GAT, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.lin1_x = nn.Linear(input_channels, hidden_channels)
self.lin1_edge = nn.Linear(input_channels, hidden_channels)
self.conv1 = GATConvW(hidden_channels, hidden_channels, heads=num_head, dropout=0.5,
edge_dim=hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
def forward(self, x, edge_index, batch, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(x, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
# x = torch.squeeze(self.proj(x))
x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
return F.log_softmax(x_1, dim=1)
class PretrainGAT(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_nodes):
super(PretrainGAT, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.lin1_concat = nn.Linear(self.hidden_channels*2, self.hidden_channels*2)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
return F.log_softmax(x_1, dim=1)
class GATLabelRelu(torch.nn.Module):
def __init__(self, input_channels, hidden_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelRelu, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.lin1_x = nn.Linear(input_channels, hidden_channels)
self.lin1_edge = nn.Linear(input_channels, hidden_channels)
self.conv1 = GATConvW(hidden_channels, hidden_channels, heads=num_head, dropout=0.5,
edge_dim=hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
# self.lin2 = nn.Linear(hidden_channels*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(x, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
# x = self.lin2(x).squeeze(-1)
x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATLabel(torch.nn.Module):
def __init__(self, input_channels, hidden_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabel, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.lin1_x = nn.Linear(input_channels, hidden_channels)
self.lin1_edge = nn.Linear(input_channels, hidden_channels)
self.conv1 = GATConvW(hidden_channels, hidden_channels, heads=num_head, dropout=0.5,
edge_dim=hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
# self.lin2 = nn.Linear(hidden_channels*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x).sigmoid()
x_edge = self.lin1_edge(x_edge).sigmoid()
x, atten_w = self.conv1(x, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
# x = self.lin2(x).squeeze(-1)
x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).sigmoid()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATFinetune(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head,
num_gene, num_celltype, num_nodes, pretrain):
super(GATFinetune, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.pretrain = pretrain
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
if self.pretrain:
self.lin1_concat = nn.Linear(self.hidden_channels*2, self.hidden_channels*2)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
else:
self.conv1 = GATConvW(self.hidden_channels, self.hidden_channels, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.lin2 = nn.Linear(self.hidden_channels*num_head, 1)
self.ln = LayerNorm(num_gene)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
if self.pretrain:
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
else:
x_concat = x.relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATConcat(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head,
num_gene, num_celltype, num_nodes, pretrain):
super(GATConcat, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.pretrain = pretrain
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
if self.pretrain:
self.lin1_concat = nn.Linear(self.hidden_channels*2, self.hidden_channels*2)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
else:
self.conv1 = GATConvW(self.hidden_channels, self.hidden_channels, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.lin2 = nn.Linear(self.hidden_channels*num_head, 1)
self.ln = LayerNorm(num_gene)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
if self.pretrain:
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
else:
x_concat = x.relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
return -1, F.log_softmax(x_1, dim=1)
class GATLabelConcat(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcat, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.lin1_concat = nn.Linear(self.hidden_channels*2, self.hidden_channels*2)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATLabelConcatMLP(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcatMLP, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.lin1_concat = nn.Linear(self.hidden_channels*2, self.hidden_channels*2)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_3 = self.lin3(x_1)
x_2 = x_3.relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_3, dim=1)
class GATLabelConcat3(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcat3, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.lin1_concat = nn.Linear(self.hidden_channels*3, self.hidden_channels*3)
self.conv1 = GATConvW(self.hidden_channels*3, self.hidden_channels*3, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
self.lin2 = nn.Linear(self.hidden_channels*3*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
x_emb = self.lin1_emb(emb)
# x_emb = emb
x_concat = torch.concat([x, x_emb, x + x_emb], dim=1)
x_concat = self.lin1_concat(x_concat).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATLabelConcat2(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcat2, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
self.lin2 = nn.Linear(self.hidden_channels*2*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
x_emb = self.lin1_emb(emb)
# x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
x = self.lin2(x).squeeze(-1)
# x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATLabelConcatPool(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcatPool, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
# self.lin2 = nn.Linear(hidden_channels*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1).relu()
x_edge = self.lin1_edge(x_edge).relu()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
# x = self.lin2(x).squeeze(-1)
x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).relu()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class GATLabelConcatSig(torch.nn.Module):
def __init__(self, input_channels, emb_channels, num_head, num_gene, num_celltype, num_nodes):
super(GATLabelConcatSig, self).__init__()
torch.manual_seed(12345)
self.num_nodes = num_nodes
self.num_gene = num_gene
self.hidden_channels = emb_channels
self.lin1_x = nn.Linear(input_channels, self.hidden_channels)
self.lin1_emb = nn.Linear(emb_channels, self.hidden_channels)
self.lin1_edge = nn.Linear(input_channels, self.hidden_channels)
self.conv1 = GATConvW(self.hidden_channels*2, self.hidden_channels*2, heads=num_head,
dropout=0.5, edge_dim=self.hidden_channels, add_self_loops=False)
self.ln = LayerNorm(num_gene)
# self.lin2 = nn.Linear(hidden_channels*num_head, 1)
self.lin3 = nn.Linear(num_gene, num_gene)
self.lin4 = nn.Linear(num_gene, num_celltype)
def forward(self, x, edge_index, batch, emb=None, edge_weight=None):
if len(x.shape) == 1:
x = x.view(x.shape[0], 1)
batchsize = len(torch.unique(batch))
x_edge = x[edge_index[0, :], :] * x[edge_index[1, :], :]
x = self.lin1_x(x)
# x_emb = self.lin1_emb(emb)
x_emb = emb
x_concat = torch.concat([x, x_emb], dim=1).sigmoid()
x_edge = self.lin1_edge(x_edge).sigmoid()
x, atten_w = self.conv1(
x_concat, edge_index, x_edge, edge_weight, return_attention_weights=True)
x = x.view(batchsize, self.num_nodes, -1)
# x = self.lin2(x).squeeze(-1)
x = torch.mean(x, dim=-1, keepdim=False)
x_1 = x[:, -self.num_gene:]
x_1 = self.ln(x_1)
x_2 = self.lin3(x_1).sigmoid()
x_2 = F.dropout(x_2, p=0.5, training=self.training)
x_2 = self.lin4(x_2)
return F.log_softmax(x_2, dim=1), F.log_softmax(x_1, dim=1)
class MyLossPairwise(nn.Module):
def __init__(self, lambda_1: float, lambda_2: float, weight_label: Tensor):
super(MyLossPairwise, self).__init__()
self.lambda_1 = lambda_1
self.lambda_2 = lambda_2
self.weight_label = weight_label
self.loss_label = torch.nn.CrossEntropyLoss(weight=weight_label)
self.loss_exp = torch.nn.KLDivLoss(log_target=False, reduction='batchmean')
self.cos = nn.CosineSimilarity(dim=-1, eps=1e-6)
def forward(self, out_label: Tensor, out_exp: Tensor, true_label: Tensor, true_exp: Tensor):
label_loss = self.loss_label(out_label, true_label)
exp_loss = self.loss_exp(out_exp, true_exp)
cos_exp = self.cos(out_exp[:, None, :], out_exp[None, :, :])
label_mat = torch.zeros(cos_exp.shape)
label_mat[(true_label[:, None] - true_label[None, :]) == 0] = 1
label_mat = label_mat.to(true_label.device)
mask_pairwise = torch.triu(torch.ones(cos_exp.shape), diagonal=1).to(true_label.device)
loss_pairwise = \
-label_mat * torch.log(torch.clip(cos_exp, 1e-10, 1.0)) - (1 - label_mat) * torch.log(torch.clip(1 - cos_exp, 1e-10, 1.0))
loss_pairwise = torch.mean(mask_pairwise * loss_pairwise)
total_loss = label_loss + self.lambda_1 * exp_loss + self.lambda_2 * loss_pairwise
return total_loss, label_loss, exp_loss, loss_pairwise
class MyLoss(nn.Module):
def __init__(self, lambda_1: float, weight_label: Tensor):
super(MyLoss, self).__init__()
self.lambda_1 = lambda_1
self.weight_label = weight_label
self.loss_label = torch.nn.CrossEntropyLoss(weight=weight_label)
self.loss_exp = torch.nn.KLDivLoss(log_target=False, reduction='batchmean')
def forward(self, out_label: Tensor, out_exp: Tensor, true_label: Tensor, true_exp: Tensor):
label_loss = self.loss_label(out_label, true_label)
exp_loss = self.loss_exp(out_exp, true_exp)
total_loss = label_loss + self.lambda_1 * exp_loss
return total_loss, label_loss, exp_loss
class MyLossExp(nn.Module):
def __init__(self):
super(MyLossExp, self).__init__()
self.loss_exp = torch.nn.KLDivLoss(log_target=False, reduction='batchmean')
def forward(self, out_exp, true_exp):
exp_loss = self.loss_exp(out_exp, true_exp)
return exp_loss
class MyLossExpMse(nn.Module):
def __init__(self):
super().__init__()
self.loss_exp = torch.nn.MSELoss(reduction='mean')
def forward(self, out_exp, true_exp):
exp_loss = self.loss_exp(out_exp, true_exp)
return exp_loss
def train(model: Module, criterion: Module, optimizer: Optimizer,
use_device: device, loader: DataLoader):
model.train()
list_loss1 = []
list_loss2 = []
list_loss = []
for data in loader: # Iterate in batches over the training dataset.
data = data.to(use_device)
# edge_tf_input = data.edge_tf.T
batch_tf = []
batchsize = len(torch.unique(data.batch))
num_peaks = data.x.shape[0] // batchsize
print(data.x.shape, data.edge_index_2.shape, data.batch.shape)
# num_tfpair = edge_tf_input.shape[1] // batchsize
# for idx_tf in range(batchsize):
# batch_tf.extend([idx_tf * num_peaks for _ in range(num_tfpair)])
# tensor_batch_tf = torch.tensor([batch_tf, batch_tf]).to(use_device)
# edge_tf_input = edge_tf_input + tensor_batch_tf
out1, out2, out_atten, out_atten2 = \
model(data.x, data.edge_index_2, data.batch)
loss, loss1, loss2 = criterion(out1, out2, data.y, data.y_exp.view(out2.shape))
loss.backward() # Derive gradients.
optimizer.step() # Update parameters based on gradients.
optimizer.zero_grad() # Clear gradients.
list_loss.append(loss.cpu().detach().numpy())
list_loss1.append(loss1.cpu().detach().numpy())
list_loss2.append(loss2.cpu().detach().numpy())
loss_cat = np.array(list_loss)
loss1_cat = np.array(list_loss1)
loss2_cat = np.array(list_loss2)
return np.mean(loss_cat), np.mean(loss1_cat), np.mean(loss2_cat)
def train_exp(model, criterion, optimizer, device, loader):
model.train()
list_loss = []
for data in tqdm(loader): # Iterate in batches over the training dataset.
data = data.to(device)
out = model(data.x, data.edge_index, data.batch)
loss = criterion(out, data.y_exp.view(out.shape))
loss.backward() # Derive gradients.
optimizer.step() # Update parameters based on gradients.
optimizer.zero_grad() # Clear gradients.
list_loss.append(loss.cpu().detach().numpy())
loss_cat = np.array(list_loss)
return np.mean(loss_cat)
def test_exp(model, device, loader):
with torch.no_grad():
list_corr = []
for data in tqdm(loader): # Iterate in batches over the training/test dataset.c
data = data.to(device)
out = model(data.x, data.edge_index, data.batch)
list_corr.append(pearsonr(torch.exp(out.cpu()), data.y_exp.view(out.shape).cpu()))
corr_cat = torch.cat(list_corr, dim=0)
return torch.median(corr_cat)
def train_gat(path_data_root: str, dataset_atac, dir_model: str,
use_device: device, hidwidth: int = 16, numhead: int = 8,
learning_rate: float = 1e-3, num_epoch: int = 20,
split_prop: float = 0.6, batch_size: int = 16, load_from_pretrained=False):
# read data
# file_atac_test = os.path.join(path_data_root, 'dataset_atac.pkl')
# with open(file_atac_test, 'rb') as r_pkl:
# dataset_atac = pickle.loads(r_pkl.read())
dataset_atac.generate_data_list(rna_exp=True)
list_graph_cortex = dataset_atac.list_graph
# path_graph_input = os.path.join(path_data_root, 'input_graph')
# dataset_atac_graph = ATACGraphDataset(path_graph_input)
torch.manual_seed(12345)
random.shuffle(list_graph_cortex)
# dataset = dataset_atac_graph.shuffle()
# split_prop = 0.8
num_split = int(len(list_graph_cortex) * split_prop)
train_dataset = list_graph_cortex[:num_split]
test_dataset = list_graph_cortex[num_split:]
# batch_size = 16
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# use_device = torch.use_device("cuda:0" if torch.cuda.is_available() else "cpu")
peaks = dataset_atac.array_peak
mask_numpy = np.array([0 if peak[:3] == 'chr' else 1 for peak in peaks])
number_gene = int(np.sum(mask_numpy))
list_weights = []
for i in range(len(dataset_atac.array_celltype)):
sub_dataset = [data for data in train_dataset if data.y == i]
sub_len = len(sub_dataset)
sub_weight = len(train_dataset)/sub_len
list_weights.append(sub_weight)
criterion = MyLossExp(1, torch.tensor(list_weights).to(use_device))
# hidwidth, numhead = 16, 8
num_node_features = 1
num_nodes = peaks.shape[0]
model = GAT(input_channels=num_node_features,
hidden_channels=hidwidth, num_head=numhead,
num_gene=number_gene,
num_nodes=num_nodes).to(use_device)
# train scReGAT
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-4)
list_loss = []
list_train_corr = []
list_test_corr = []
for epoch in range(num_epoch):
loss_t = train_exp(model, criterion, optimizer, use_device, train_loader)