-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_keras_redefined_loss.py
2521 lines (2315 loc) · 145 KB
/
train_keras_redefined_loss.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
# data_train.py
import re
# from resVAE.resvae import resVAE
# import resVAE.utils as cutils
# from resVAE.config import config
# import resVAE.reporting as report
import torchvision
import torch
# from fastai.basic_data import DataBunch
# from fastai.basic_train import Learner
# from fastai.layers import *
# from fastai.metrics import accuracy
# from fastai.train import ShowGraph
from MeiNN.MeiNN import MeiNN, gene_to_residue_or_pathway_info
# from MeiNN.MeiNN_pytorch import MeiNN_pytorch
from MeiNN.config import config
import os
import json
import numpy as np
import pandas as pd
import csv # 调用数据保存文件
import pickle
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# import TabularAutoEncoder
# import VAE
# import tensorflow.compat.v1 as tf
# tf.disable_v2_behavior()
import tensorflow as tf
# tf.compat.v1.disable_eager_execution()#newly-added-3-27
import torch
from torch import nn
# import torchvision
from torch.autograd import Variable
# import AutoEncoder
import math
import warnings
import AutoEncoder as AE
from time import time
# import tensorflow.keras as keras
from keras import layers
# from keras import objectives
from keras import losses
from keras import regularizers
from keras import backend as K
from keras.models import Model # 泛型模型
from keras.layers import Dense, Input
from keras.models import load_model
from tensorboardX import SummaryWriter
import tools
import min_norm_solvers
from torch.utils.data import Dataset
import random
#from methods.weight_methods import WeightMethods
import re
import umap
import matplotlib.pyplot as plt
from losses import SupConLoss
logger = SummaryWriter(log_dir="tensorboard_log/")
warnings.filterwarnings("ignore")
CLASSIFIER_FACTOR=10000
CONTRASTIVE_FACTOR=50000
REGULARIZATION_FACTOR=0.0001
TO_PIN_MEMORY=False #True
REG_SIGN="^"
MULTI_TASK_SIGN="~"
SINGLE_TASK_UPPER_BOUND_WEIGHT=0.1
evaluate_weight_site_pathway_step=100
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def extract_value_between_signs(input_string, sign="$"):
if sign == ".":
pattern = r"\.(\d+)(?:\.|$)"
elif sign == "@":
pattern = fr"{re.escape(sign)}(.*?){re.escape(sign)}"
else:
pattern = fr"{re.escape(sign)}(\d+(?:\.\d+)?){re.escape(sign)}"
match = re.search(pattern, input_string)
if match:
if sign == ".":
num_str = match.group(1)
num_digits = len(num_str)
num = int(num_str)
return num / (10 ** num_digits)
elif sign == "@":
return match.group(1)
else:
return float(match.group(1)) if "." in match.group(1) else int(match.group(1))
else:
return None
def get_condition_value(row):
for i, value in enumerate(row):
if value == 1 or value == 0:
return i * 2 + value
def multi_label_to_one_dim(y_train):
umap_labels = ["IBD_F", "IBD_T", "MS_F", "MS_T", "Psoriasis_F", "Psoriasis_T", "RA_F", "RA_T", "SLE_F", "SLE_T", "diabetes1_F", "diabetes1_T"]
new_y_train_df = pd.DataFrame(y_train.T.apply(get_condition_value, axis=1)).T
print(new_y_train_df)
#new_y_train_df.columns = ["Condition"]
new_y_train_df.index.name = "Index"
return new_y_train_df
def draw_umap(gene_data_train,y_train,num_of_selected_residue,stage_info="original",training_setting_info=""):
umap_labels = ["IBD_F", "IBD_T", "MS_F", "MS_T", "Psoriasis_F", "Psoriasis_T", "RA_F", "RA_T", "SLE_F", "SLE_T", "diabetes1_F", "diabetes1_T"]
#from sklearn.datasets import load_digits
#digits = load_digits()
print(y_train)
print(y_train.shape)
'''
Ground TruthIBD
Ground TruthMS
Ground TruthPsoriasis
Ground TruthRA
Ground TruthSLE
Ground Truthdiabetes1
'''
'''
y_train_onehot = pd.get_dummies(y_train.T, columns = ['Ground TruthIBD','Ground TruthMS','Ground TruthPsoriasis','Ground TruthRA',
'Ground TruthSLE','Ground Truthdiabetes1'], drop_first=True)
print(y_train_onehot )
conditions = ['IBD', 'MS', 'Psoriasis', 'RA', 'SLE', 'diabetes1']
y_train_columns_list = y_train.T.columns.tolist()
merged_y_train = {f'{condition}_{i + 1}': y_train.T.loc[:, 'Ground Truth'+condition].iloc[i] for i in range(len(y_train_columns_list)) for condition in conditions}
new_merged_y_train = pd.DataFrame(merged_y_train, index=[0])
print(new_merged_y_train)
y_train_onehot=y_train_onehot.replace([1,0],[True,False])
print(y_train_onehot )'''
# Apply the function to the DataFrame and store the results in a new DataFrame with a single row
new_y_train_df = pd.DataFrame(y_train.T.apply(get_condition_value, axis=1)).T
print(new_y_train_df)
#new_y_train_df.columns = ["Condition"]
new_y_train_df.index.name = "Index"
print(new_y_train_df)
#for n_neighbours in (2, 5, 10, 20, 50, 100, 200):
umap_embedding = umap.UMAP(random_state=42).fit_transform(gene_data_train.T,new_y_train_df.T)#,y_train_onehot)#dataset.cpu())#gene_data_train.T)
#umap_embedding_2 = umap.UMAP(random_state=42).fit_transform(gene_data_train.T)
###
from sklearn.cluster import KMeans
if "original" in stage_info:
kmeans = KMeans(n_clusters=12, random_state=0).fit(umap_embedding)
kmeans_fit_predict=KMeans(n_clusters=12, random_state=0).fit_predict(umap_embedding,y_train)
####
plt.clf() # clear figure
plt.cla() # clear axis
plt.close() # close window
# Prepare the legend labels and colors
# Create a scatter plot of the UMAP embeddings
'''
plt.scatter(umap_embedding[:, 0], umap_embedding[:, 1],c=new_y_train_df.T, cmap='Spectral', s=5,label=umap_labels)
plt.gca().set_aspect('equal', 'datalim')'''
#plt.colorbar(boundaries=np.arange(11)-0.5).set_ticks(["IBD_F","IBD_T","MS_F","MS_T","Psoriasis_F","Psoriasis_T","RA_F","RA_T","SLE_F","SLE_T","diabetes1_F","diabetes1_T"])#np.arange(10)
colors = plt.cm.Spectral(np.linspace(0, 1, len(umap_labels)))
# Create the scatter plot
for label, color in zip(range(1, 13), colors):
indices = (new_y_train_df.T == label).values.ravel()
plt.scatter(umap_embedding[indices, 0], umap_embedding[indices, 1], c=[color], cmap='Spectral', s=5, label=umap_labels[label - 1])
plt.gca().set_aspect('equal', 'datalim')
# Add the legend
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='small')
plt.title('UMAP projection of the gene_data_train dataset '+stage_info+' (num of site='+str(num_of_selected_residue)+')', fontsize=12)
# Save the plot as a PNG image
umap_dir_path = "./umap/"
if not os.path.exists(umap_dir_path):
os.makedirs(umap_dir_path)
print("Directory", umap_dir_path, "created.")
else:
print("Directory", umap_dir_path, "already exists.")
output_image_path = umap_dir_path+stage_info+"-site-"+str(num_of_selected_residue)+"-"+training_setting_info+"-umap.png" #"original
plt.savefig(output_image_path, dpi=300, bbox_inches='tight')
# Display the plot in the notebook (optional)
#plt.show()
if "original" in stage_info:
return kmeans,kmeans_fit_predict
else:
return
class CustomDataset(Dataset):
def __init__(self, data,label,toDebug=False):
self.label = label
self.data = data
self.toDebug=toDebug
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
#img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
#image = read_image(img_path)
label = self.label[idx, :]
data = self.data[idx,:]
if self.toDebug:
print("DEBUG: inside dataset:")
print("label")
print(label)
print("data")
print(data)
return data, label
def mkdir(path):
import os
# remove first blank space
path = path.strip()
# remove \ at the end
path = path.rstrip("\\")
# judge whether directory exists
# exist True
# not exist False
isExists = os.path.exists(path)
# judge the result
if not isExists:
# if not exist, then create directory
os.makedirs(path)
print(path + " directory created successfully.")
return True
else:
# if directory exists, don't create and print it already exists
#print(path + " directory already exists.")
return False
def origin_data(data):
return data
def square_data(data):
return data ** 2
def log_data(data):
return np.log(data + 1e-5)
def radical_data(data):
return data ** (1 / 2)
def cube_data(data):
return data ** 3
toPrintInfo=False
global_iter_num =0
def return_reg_loss(ae,skip_connection_mode="^dec"):
reg_loss = 0
reg_mode_list=skip_connection_mode.split(REG_SIGN)
if len(reg_mode_list)>=2:
reg_mode=reg_mode_list[1]
else:
reg_mode=""
if reg_mode=="all":
for i, param in enumerate(ae.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
elif reg_mode=="dec":
for i, param in enumerate(ae.decoder1.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
for i, param in enumerate(ae.decoder2.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
elif reg_mode=="sftde":
for i, param in enumerate(ae.decoder1.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
for i, param in enumerate(ae.decoder2.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
elif reg_mode=="sftall":
for i, param in enumerate(ae.decoder1.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
for i, param in enumerate(ae.decoder2.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
else :#reg_mode=="sftde":
pass
'''
for i, param in enumerate(ae.decoder1.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))
for i, param in enumerate(ae.decoder2.parameters()):
if toPrintInfo:
print("%d-th layer:" % i)
# print(name)
print("param:")
print(param.shape)
reg_loss += torch.sum(torch.abs(param))'''
return reg_loss
'''
def matrix_ones_to_val(matrix,to_value,percentage,count,option=""):
return matrix
def random_mask_matrix_ones(matrix,to_value,percentage,count,option=""):
return matrix
def evaluate_accuracy_predict_random_mask_matrix_ones(matrix,masked_matrix,true_matrix):
predict_mask_accuracy=0.0
return predict_mask_accuracy
'''
import pandas as pd
import numpy as np
def matrix_zeros_to_val(matrix, to_value):
"""
Replace all the zeros in the matrix to `to_value`.
Args:
matrix (pd.DataFrame): The input matrix (Pandas DataFrame)
to_value (int or float): The value to replace zeros with
Returns:
pd.DataFrame: The processed matrix with zeros replaced by `to_value`
"""
return matrix.replace(0, to_value)
def random_mask_matrix_ones_to_val(matrix, to_value, percentage, count, option=""):
"""
Replace a percentage or a count of ones in the matrix with `to_value`.
Args:
matrix (pd.DataFrame): The input matrix (Pandas DataFrame)
to_value (int or float): The value to replace ones with
percentage (float): Percentage of ones to replace (0 to 1)
count (int): Number of ones to replace
option (str): "p" for percentage, "c" for count
Returns:
pd.DataFrame: The processed matrix with ones replaced by `to_value`
list: The list of masked positions (each element is a 2D [x, x] representing row and column)
"""
masked_matrix = matrix.copy()
ones_positions = np.argwhere(matrix.to_numpy() == 1)
masked_positions = []
if option == "p":
count = int(len(ones_positions) * percentage)
elif option == "c":
assert count <= len(ones_positions), "Count must be less or equal to the total number of 1s in the matrix."
np.random.shuffle(ones_positions)
for i in range(count):
masked_positions.append(ones_positions[i].tolist())
masked_matrix.iat[masked_positions[-1][0], masked_positions[-1][1]] = to_value
return masked_matrix, masked_positions
def evaluate_accuracy_predict_random_mask_matrix_ones(pred_matrix, true_matrix, masked_matrix, masked_position_list, threshold):
"""
Evaluate accuracy and other statistics of `pred_matrix` compared to `true_matrix`.
Args:
pred_matrix (pd.DataFrame): The predicted matrix (Pandas DataFrame)
true_matrix (pd.DataFrame): The true matrix (Pandas DataFrame)
masked_matrix (pd.DataFrame): The masked matrix (Pandas DataFrame)
masked_position_list (list): The list of masked positions
threshold (float): Threshold value for comparison
Returns:
list: learned_percentile_list
float: Average of learned_percentile_list
np.ndarray: Distribution of all the weights of pred_matrix
np.ndarray: Distribution of elements of pred_matrix which are on the position of 1s in true_matrix
np.ndarray: Distribution of elements of pred_matrix which are on the position of 0s of true_matrix
np.ndarray: Distribution of elements of pred_matrix which are on the position of masked_position_list
"""
learned_percentile_list = []
for position in masked_position_list:
row, col = position
if pred_matrix.iat[row, col] >= threshold:
learned_percentile_list.append(1)
else:
learned_percentile_list.append(0)
average_learned_percentile = np.mean(learned_percentile_list)
all_weights = pred_matrix.values.flatten()
one_positions = np.argwhere(true_matrix.to_numpy() == 1)
zero_positions = np.argwhere(true_matrix.to_numpy() == 0)
ones_distribution = np.array([pred_matrix.iat[row, col] for row, col in one_positions])
zeros_distribution = np.array([pred_matrix.iat[row, col] for row, col in zero_positions])
masked_distribution = np.array([pred_matrix.iat[row, col] for row, col in masked_position_list])
return (learned_percentile_list,
average_learned_percentile,
all_weights,
ones_distribution,
zeros_distribution,
masked_distribution)
def assign_multi_task_weight(model,datasetNameList,y_pred_list,y_masked_splited,mask_splited,criterion,log_info,validation_info,single_task_accu_upper_bound_list=[0.93,0.73,0.80,0.94,0.79,0.98],sample_size_list=[53,88,79,49,160,118],multi_task_training_policy="~uniform",skip_connection_mode=""):
y_pred_masked_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
loss_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
pred_loss_total_splited_sum = 0
loss_single_classifier = 0
loss_sum=0
if "#" in skip_connection_mode:
contrastive_criterion=SupConLoss()
for i in range(len(datasetNameList)):
y_pred_masked_list.append(y_pred_list[i].to(device).T * (mask_splited[i].to(device).squeeze()).squeeze())
current_loss=criterion(y_pred_masked_list[i].T.squeeze(), y_masked_splited[i].to(device).squeeze())
loss_list.append(current_loss)
loss_sum+=current_loss
####################################################################
[accuracy, split_accuracy_list]=validation_info
# After "~" is the multi-task assignment:
# "~uni"
# "~ran"
# "~re-val"
# "pwre-val"
# "re-ss"
# "norm"
# "s-gdnm"simple gradnorm
# "DRO"
assign_weight_policy_list=multi_task_training_policy.split(MULTI_TASK_SIGN)
if len(assign_weight_policy_list)>=2:
assign_weight_policy=assign_weight_policy_list[1]
else:
assign_weight_policy=""
assign_weight_value_list=len(datasetNameList)*[1.0]
if assign_weight_policy=="uni":
assign_weight_value_list=[1.0 for i in range(len(datasetNameList))]
elif assign_weight_policy=="ran": #TODO:random
assign_weight_value_list=[random.random() for i in range(len(datasetNameList))]
elif assign_weight_policy=="re-val": #TODO:reversed porportional to validation accu
assign_weight_value_list=[1.0-split_accuracy_list[i] for i in range(len(datasetNameList))]
elif assign_weight_policy=="pwre-val": #TODO:piece-wise reversed validation accu
#assign_weight_value_list=[]
for i in range(len(datasetNameList)):
w=SINGLE_TASK_UPPER_BOUND_WEIGHT
s=single_task_accu_upper_bound_list[i]
x=split_accuracy_list[i]
if x<=s:
assign_weight_value_list[i]=(w-1)/s*x+1
else:
assign_weight_value_list[i]=-w/(s-1)*x+w/(1-s)
elif assign_weight_policy=="re-ss": #TODO:reverse porportional to task sample size
assign_weight_value_list=[1.0/sample_size_list[i] for i in range(len(datasetNameList))]
elif assign_weight_policy=="norm": #TODO:normalize the scale of each task #TODO:gradnorm
for i in range(len(datasetNameList)): #TODO:make sure,model.encoder4, it's last shared layer
assign_weight_value_list[i]=1.0/torch.norm(torch.autograd.grad(loss_list[i], model.encoder4.parameters() , retain_graph=True, create_graph=True)[0])
elif assign_weight_policy=="s-gdnm": #TODO:simple gradnorm ,fix whether has bug
for i in range(len(datasetNameList)): #TODO:make sure,model.encoder4, it's last shared layer
assign_weight_value_list[i]=torch.norm(torch.autograd.grad(loss_list[i], model.encoder4.parameters() , retain_graph=True, create_graph=True)[0])
elif assign_weight_policy=="DRO": #TODO:DRO-like, higher loss, higher weight
assign_weight_value_list=[loss_list[i]/loss_sum for i in range(len(datasetNameList))]
elif assign_weight_policy=="L2":
assign_weight_value_list=loss_list[i]
else :#uniform
assign_weight_value_list=[1.0 for i in range(len(datasetNameList))]
#####################################################
for i in range(len(datasetNameList)):
temp_single_task_loss = criterion(y_pred_masked_list[i].to(device).T.squeeze(),
y_masked_splited[i].to(device).squeeze())
pred_loss_total_splited_sum += assign_weight_value_list[i]*temp_single_task_loss
logger.add_scalar(log_info+"%d-th task %s loss" % (i, datasetNameList[i]),
temp_single_task_loss, global_step=global_iter_num)
logger.add_scalar(log_info+"%d-th weight*task %s loss" % (i, datasetNameList[i]),
assign_weight_value_list[i]*temp_single_task_loss, global_step=global_iter_num)
return y_pred_masked_list,loss_list,pred_loss_total_splited_sum
def single_train_process(num_epochs,data_loader,datasetNameList,ae,gene_data_train_Tensor,toMask,y_train_T_tensor,criterion,
path,date,pth_name,toDebug,global_iter_num,log_stage_name,code,toValidate,gene_data_valid_Tensor,valid_label,
multi_task_training_policy,learning_rate_list,skip_connection_mode,umap_draw_step,num_of_selected_residue,y_train,mask_option,my_gene_to_residue_info):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
loss_list = []
for epoch in range(num_epochs):
for i_data_batch, (images,y_train_T_tensor) in enumerate(data_loader): # for i, (images, _) in enumerate(data_loader):
# flatten the image
images = AE.to_var(images.view(images.size(0), -1))
images = images.float()
# forward
if len(datasetNameList) == 6:
out, y_pred_list, embedding = ae(images)#gene_data_train_Tensor.T)#partial batch
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T)#for validation
#umap
if "umapet" in skip_connection_mode and (epoch+1)%umap_draw_step ==0:
print("embedding.shape")
print(embedding.shape)
draw_umap(embedding.T.cpu().detach().numpy(),y_train,num_of_selected_residue,stage_info="3ndstage-train-epo-"+str(epoch),training_setting_info=date)
##
if mask_option is not None and (epoch+1)%evaluate_weight_site_pathway_step ==0:
my_gene_to_residue_info.evaluate_weight_site_pathway(ae,date+"3rd-epo"+str(epoch))
#to GPU
#y_pred_list=y_pred_list.to(device)
#valid_y_pred_list=valid_y_pred_list.to(device)
if toMask:
mask = y_train_T_tensor.ne(0.5)
y_masked = y_train_T_tensor * mask
if toDebug:
print("DEBUG:y_train_T_tensor is:")
print(y_train_T_tensor.shape)
print("DEBUG: mask is:")
print(mask.shape)
print("DEBUG: y_masked is:")
print(y_masked.shape)
y_masked_splited = torch.split(y_masked, 1, 1)
mask_splited = torch.split(mask, 1, 1)
if toDebug:
print("len of y_masked_splited%d" % len(y_masked_splited))
print("DEBUG: y_masked_splited is:")
print(y_masked_splited[0].shape)
print("DEBUG: mask_splited is:")
print("len of mask_splited%d" % len(mask_splited))
print(mask_splited[0].shape)
#################################
'''
y_pred_masked_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
loss_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
pred_loss_total_splited_sum = 0
loss_single_classifier = 0
for i in range(len(datasetNameList)):
y_pred_masked_list.append(y_pred_list[i].to(device).T * (mask_splited[i].to(device).squeeze()).squeeze())
loss_list.append(criterion(y_pred_masked_list[i].T.squeeze(), y_masked_splited[i].to(device).squeeze()))
pred_loss_total_splited_sum += criterion(y_pred_masked_list[i].to(device).T.squeeze(),
y_masked_splited[i].to(device).squeeze())
logger.add_scalar(date+code+" "+log_stage_name+": %d-th single dataset %s loss" % (i, datasetNameList[i]),
criterion(y_pred_masked_list[i].to(device).T.squeeze(),
y_masked_splited[i].to(device).squeeze()), global_step=global_iter_num)
'''#commented 2023-4-23 for different multi-task weight assignment
if 'accuracy' not in locals().keys():
accuracy=0.0
if 'split_accuracy_list' not in locals().keys():
split_accuracy_list=[0.0 for i in range(len(datasetNameList))]
y_pred_masked_list,loss_list,pred_loss_total_splited_sum=assign_multi_task_weight(ae,datasetNameList,y_pred_list,y_masked_splited,mask_splited,criterion,(date+code+" "+log_stage_name),[accuracy, split_accuracy_list],
multi_task_training_policy=multi_task_training_policy,skip_connection_mode=skip_connection_mode)
##################################
reg_loss = return_reg_loss(ae,skip_connection_mode)
loss_single_classifier = pred_loss_total_splited_sum * 100000 + reg_loss * 0.0001 #TODO:add autoencoder reconstruction loss
if "#" in skip_connection_mode:
contrastive_criterion=SupConLoss()
loss_single_classifier+= contrastive_criterion(embedding)*CONTRASTIVE_FACTOR
if "VAE" in skip_connection_mode:
loss_single_classifier +=ae.kl_divergence
print(pth_name+" loss: %f" % loss_single_classifier.item())
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, ae.parameters()), lr=learning_rate_list[2])#1e-3
if "ROnP" in multi_task_training_policy:
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'max',factor=0.9,patience=40) # added 23-1-2 for special training policy
optimizer.zero_grad()
loss_single_classifier.backward(retain_graph=True)
# loss_single_classifier_loss_list[dataset_id].append(loss_single_classifier.item())
optimizer.step()
global_iter_num = epoch * len(
data_loader) + i_data_batch + 1 # calculate it's which step start from training
if "*" in skip_connection_mode:
ae.save_site_gene_pathway_weight_visualization(info=log_stage_name+" epoch "+str(global_iter_num))
if toValidate:
normalized_pred_out, num_wrong_pred, accuracy, split_accuracy_list ,auroc_list= tools.evaluate_accuracy_list(
datasetNameList, valid_label, valid_y_pred_list,toPrint=False) # added for validation data#2023-1-8
if "ROnP" in multi_task_training_policy:
scheduler.step(accuracy)
logger.add_scalar(date + code + " " + log_stage_name + ": total validation accuracy",
accuracy, global_step=global_iter_num)
for i in range(len(datasetNameList)):# added for validation data#2023-1-8
logger.add_scalar(date + code + " " + log_stage_name + ": %d-th single dataset %s validation accuracy"%(i, datasetNameList[i]),
split_accuracy_list[i], global_step=global_iter_num)
logger.add_scalar(date+code+" "+log_stage_name+": autoencoder reconstruction loss", criterion(out, images), global_step=global_iter_num)
logger.add_scalar(date+code+" "+log_stage_name+": regularization loss", reg_loss, global_step=global_iter_num)
logger.add_scalar(date+code+" "+log_stage_name+": classifier predction loss", pred_loss_total_splited_sum, global_step=global_iter_num)
logger.add_scalar(date+code+" "+log_stage_name+": total train loss", loss_single_classifier.item(), global_step=global_iter_num)
for name, param in ae.named_parameters():
logger.add_histogram(date+code+" "+log_stage_name+": "+name, param.data.cpu().numpy(), global_step=global_iter_num)
torch.save(ae, path + date + pth_name+".pth")#"single-classifier-trained.pth"
if "MGDA" in multi_task_training_policy:
torch.save(ae, path + date + pth_name + "1.pth")
loss_now=0
grads = {}#[None]*len(datasetNameList)
scale = [0.0]*len(datasetNameList)
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, ae.parameters()),
lr=learning_rate_list[2]) # 1e-3
for epoch in range(num_epochs,num_epochs*2):
for i_data_batch, (images,y_train_T_tensor) in enumerate(data_loader): # for i, (images, _) in enumerate(data_loader):
# flatten the image
images = AE.to_var(images.view(images.size(0), -1))
images = images.float()
# forward
if len(datasetNameList) == 6:
out, y_pred_list, embedding = ae(gene_data_train_Tensor.T)#partial batch
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T) # for validation
if toMask:
mask = y_train_T_tensor.ne(0.5)
y_masked = y_train_T_tensor * mask
if toDebug:
print("DEBUG:y_train_T_tensor is:")
print(y_train_T_tensor.shape)
print("DEBUG: mask is:")
print(mask.shape)
print("DEBUG: y_masked is:")
print(y_masked.shape)
y_masked_splited = torch.split(y_masked, 1, 1)
mask_splited = torch.split(mask, 1, 1)
if toDebug:
print("len of y_masked_splited%d" % len(y_masked_splited))
print("DEBUG: y_masked_splited is:")
print(y_masked_splited[0].shape)
print("DEBUG: mask_splited is:")
print("len of mask_splited%d" % len(mask_splited))
print(mask_splited[0].shape)
y_pred_masked_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
loss_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
pred_loss_total_splited_sum = 0
loss_single_classifier = 0
single_task_loss=[0]*len(datasetNameList)
for i in range(len(datasetNameList)):
optimizer.zero_grad()
y_pred_masked_list.append(y_pred_list[i].T * (mask_splited[i].squeeze()).squeeze())
single_task_loss[i] = criterion(y_pred_masked_list[i].T.squeeze(),
y_masked_splited[i].squeeze())
loss_list.append(single_task_loss[i])
pred_loss_total_splited_sum += single_task_loss[i]#this is loss for single task
loss_now=single_task_loss[i]
loss_now.backward(retain_graph=True)
logger.add_scalar(date + code + " " + log_stage_name + ": %d-th single dataset %s loss" % (
i, datasetNameList[i]),single_task_loss[i], global_step=global_iter_num)
grads[i] = []
if "unet" in skip_connection_mode:
for param in ae.encoder1.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder2.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder3.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder4.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
else:#no "unet" type skip connection, architecture is a whole en/decoder
for param in ae.encoder.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
print(grads)
# Frank-Wolfe iteration to compute scales. 利用FW算法计算loss的scale
sol, min_norm = min_norm_solvers.MinNormSolver.find_min_norm_element([grads[i] for i in range(len(datasetNameList))])
for i, t in enumerate(datasetNameList):
scale[i] = float(sol[i])
# Scaled back-propagation 按计算的scale缩放loss并反向传播
optimizer.zero_grad()
#rep, _ = model['rep'](images, mask)
if len(datasetNameList) == 6:
out, y_pred_list, embedding = ae(images)#gene_data_train_Tensor.T)#partial batch
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T) # for validation
y_pred_masked_list=[]*len(datasetNameList)
single_task_loss=[]*len(datasetNameList)
for i, t in enumerate(datasetNameList):
#out_t, _ = model[t](rep, masks[t])
#loss_t = loss_fn[t](out_t, labels[t])
#loss_data[t] = loss_t.data[0]
if toMask:
mask = y_train_T_tensor.ne(0.5)
y_masked = y_train_T_tensor * mask
y_masked_splited = torch.split(y_masked, 1, 1)
mask_splited = torch.split(mask, 1, 1)
y_pred_masked_list[i]=(y_pred_list[i].T * (mask_splited[i].squeeze()).squeeze())
single_task_loss[i] = criterion(y_pred_masked_list[i].T.squeeze(),
y_masked_splited[i].squeeze())
loss_t=single_task_loss[i]
if i > 0:
loss_now = loss_now + scale[i] * loss_t
else:
loss_now = scale[i] * loss_t
if "#" in skip_connection_mode:
contrastive_criterion=SupConLoss()
loss_now+= contrastive_criterion(embedding)*CONTRASTIVE_FACTOR
loss_now.backward(retain_graph=True)
optimizer.step()
reg_loss = return_reg_loss(ae,skip_connection_mode)
loss_single_classifier = pred_loss_total_splited_sum * 100000 + reg_loss * 0.0001
print("MGDA"+pth_name + " loss: %f" % loss_now.item())
#optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, ae.parameters()),
# lr=learning_rate_list[2]) # 1e-3
#optimizer.zero_grad()
#loss_single_classifier.backward(retain_graph=True)
# loss_single_classifier_loss_list[dataset_id].append(loss_single_classifier.item())
#optimizer.step()
global_iter_num = epoch * len(
data_loader) + i_data_batch + 1 # calculate it's which step start from training
if "*" in skip_connection_mode:
ae.save_site_gene_pathway_weight_visualization(info=log_stage_name+"MGDA epoch "+str(global_iter_num))
if toValidate:
normalized_pred_out, num_wrong_pred, accuracy, split_accuracy_list, auroc_list = tools.evaluate_accuracy_list(
datasetNameList, valid_label, valid_y_pred_list,
toPrint=False) # added for validation data#2023-1-8
logger.add_scalar("MGDA "+date + code + " " + log_stage_name + ": total validation accuracy",
accuracy, global_step=global_iter_num)
for i in range(len(datasetNameList)): # added for validation data#2023-1-8
logger.add_scalar(
"MGDA "+date + code + " " + log_stage_name + ": %d-th single dataset %s validation accuracy" % (
i, datasetNameList[i]),
split_accuracy_list[i], global_step=global_iter_num)
logger.add_scalar("MGDA "+date + code + " " + log_stage_name + ": autoencoder reconstruction loss",
criterion(out, images), global_step=global_iter_num)
logger.add_scalar("MGDA "+date + code + " " + log_stage_name + ": regularization loss", reg_loss,
global_step=global_iter_num)
logger.add_scalar("MGDA "+date + code + " " + log_stage_name + ": classifier predction loss",
loss_now.item(), global_step=global_iter_num)
logger.add_scalar("MGDA "+date + code + " " + log_stage_name + ": total train loss",
loss_now.item(), global_step=global_iter_num)
for name, param in ae.named_parameters():
logger.add_histogram("MGDA "+date + code + " " + log_stage_name + ": " + name, param.data.numpy(),
global_step=global_iter_num)
#torch.save(ae, path + date + pth_name + ".pth") # "single-classifier-trained.pth"
torch.save(ae, path + date + " MGDA "+pth_name + ".pth")
if "NashMTL" in multi_task_training_policy: #TODO: Apply NashMTL
torch.save(ae, path + date + pth_name + "1.pth")
loss_now=0
grads = {}#[None]*len(datasetNameList)
scale = [0.0]*len(datasetNameList)
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, ae.parameters()),
lr=learning_rate_list[0]) # 1e-3#lr=learning_rate_list[2]
for epoch in range(num_epochs,num_epochs*2):
for i_data_batch, (images,y_train_T_tensor) in enumerate(data_loader): # for i, (images, _) in enumerate(data_loader):
# flatten the image
images = AE.to_var(images.view(images.size(0), -1))
images = images.float()
# forward
if len(datasetNameList) == 6:
out, y_pred_list, embedding = ae(images)#gene_data_train_Tensor.T)#partial batch
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T) # for validation
if toMask:
mask = y_train_T_tensor.ne(0.5)
y_masked = y_train_T_tensor * mask
if toDebug:
print("DEBUG:y_train_T_tensor is:")
print(y_train_T_tensor.shape)
print("DEBUG: mask is:")
print(mask.shape)
print("DEBUG: y_masked is:")
print(y_masked.shape)
y_masked_splited = torch.split(y_masked, 1, 1)
mask_splited = torch.split(mask, 1, 1)
if toDebug:
print("len of y_masked_splited%d" % len(y_masked_splited))
print("DEBUG: y_masked_splited is:")
print(y_masked_splited[0].shape)
print("DEBUG: mask_splited is:")
print("len of mask_splited%d" % len(mask_splited))
print(mask_splited[0].shape)
y_pred_masked_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
loss_list = [] # [y_pred_list[:,0]*len(datasetNameList)]
pred_loss_total_splited_sum = 0
loss_single_classifier = 0
single_task_loss=[0]*len(datasetNameList)
for i in range(len(datasetNameList)):
optimizer.zero_grad()
y_pred_masked_list.append(y_pred_list[i].T * (mask_splited[i].squeeze()).squeeze())
single_task_loss[i] = criterion(y_pred_masked_list[i].T.squeeze(),
y_masked_splited[i].squeeze())
loss_list.append(single_task_loss[i])
pred_loss_total_splited_sum += single_task_loss[i]#this is loss for single task
loss_now=single_task_loss[i]
loss_now.backward(retain_graph=True)
logger.add_scalar(date + code + " " + log_stage_name + ": %d-th single dataset %s loss" % (
i, datasetNameList[i]),single_task_loss[i], global_step=global_iter_num)
grads[i] = []
if "unet" in skip_connection_mode:
for param in ae.encoder1.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder2.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder3.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
for param in ae.encoder4.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
else:#no "unet" type skip connection, architecture is a whole en/decoder
for param in ae.encoder.parameters():
if param.grad is not None:
grads[i].append(Variable(param.grad.data.clone(),
requires_grad=False)) # mask pretrained model weight
print(grads)
# Frank-Wolfe iteration to compute scales. 利用FW算法计算loss的scale
sol, min_norm = min_norm_solvers.MinNormSolver.find_min_norm_element([grads[i] for i in range(len(datasetNameList))])
for i, t in enumerate(datasetNameList):
scale[i] = float(sol[i])
# Scaled back-propagation 按计算的scale缩放loss并反向传播
optimizer.zero_grad()
#rep, _ = model['rep'](images, mask)
if len(datasetNameList) == 6:
out, y_pred_list, embedding = ae(images)#gene_data_train_Tensor.T)#partial batch
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T) # for validation
y_pred_masked_list=[]*len(datasetNameList)
single_task_loss=[]*len(datasetNameList)
for i, t in enumerate(datasetNameList):
#out_t, _ = model[t](rep, masks[t])
#loss_t = loss_fn[t](out_t, labels[t])
#loss_data[t] = loss_t.data[0]
if toMask:
mask = y_train_T_tensor.ne(0.5)
y_masked = y_train_T_tensor * mask
y_masked_splited = torch.split(y_masked, 1, 1)
mask_splited = torch.split(mask, 1, 1)
y_pred_masked_list[i]=(y_pred_list[i].T * (mask_splited[i].squeeze()).squeeze())
single_task_loss[i] = criterion(y_pred_masked_list[i].T.squeeze(),
y_masked_splited[i].squeeze())
loss_t=single_task_loss[i]
if i > 0:
loss_now = loss_now + scale[i] * loss_t
else:
loss_now = scale[i] * loss_t
if "#" in skip_connection_mode:
contrastive_criterion=SupConLoss()
loss_now+= contrastive_criterion(embedding)*CONTRASTIVE_FACTOR
loss_now.backward(retain_graph=True)
optimizer.step()
reg_loss = return_reg_loss(ae,skip_connection_mode)
loss_single_classifier = pred_loss_total_splited_sum * 100000 + reg_loss * 0.0001
print("NashMTL "+pth_name + " loss: %f" % loss_now.item())
#optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, ae.parameters()),
# lr=learning_rate_list[2]) # 1e-3
#optimizer.zero_grad()
#loss_single_classifier.backward(retain_graph=True)
# loss_single_classifier_loss_list[dataset_id].append(loss_single_classifier.item())
#optimizer.step()
global_iter_num = epoch * len(
data_loader) + i_data_batch + 1 # calculate it's which step start from
if "*" in skip_connection_mode:
ae.save_site_gene_pathway_weight_visualization(info=log_stage_name+"NashMTL epoch "+str(global_iter_num))
if toValidate:
normalized_pred_out, num_wrong_pred, accuracy, split_accuracy_list, auroc_list = tools.evaluate_accuracy_list(
datasetNameList, valid_label, valid_y_pred_list,
toPrint=False) # added for validation data#2023-1-8
logger.add_scalar("NashMTL "+date + code + " " + log_stage_name + ": total validation accuracy",
accuracy, global_step=global_iter_num)
for i in range(len(datasetNameList)): # added for validation data#2023-1-8
logger.add_scalar(
"NashMTL "+date + code + " " + log_stage_name + ": %d-th single dataset %s validation accuracy" % (
i, datasetNameList[i]),
split_accuracy_list[i], global_step=global_iter_num)
logger.add_scalar("NashMTL "+date + code + " " + log_stage_name + ": autoencoder reconstruction loss",
criterion(out, images), global_step=global_iter_num)
logger.add_scalar("NashMTL "+date + code + " " + log_stage_name + ": regularization loss", reg_loss,
global_step=global_iter_num)
logger.add_scalar("NashMTL "+date + code + " " + log_stage_name + ": classifier predction loss",
loss_now.item(), global_step=global_iter_num)
logger.add_scalar("NashMTL "+date + code + " " + log_stage_name + ": total train loss",
loss_now.item(), global_step=global_iter_num)
for name, param in ae.named_parameters():
logger.add_histogram("NashMTL "+date + code + " " + log_stage_name + ": " + name, param.data.numpy(),
global_step=global_iter_num)
#torch.save(ae, path + date + pth_name + ".pth") # "single-classifier-trained.pth"
torch.save(ae, path + date + " NashMTL "+pth_name + ".pth")
return ae,loss_list,global_iter_num
# Define the single_task_training_one_epoch function
def single_task_training_one_epoch(stageName,datasetNameList,ae, optimizer, criterion, data_loader, task_idx, num_epochs, dataset,batch_size,batch_size_ratio,gene_data_train,path,date,model_dict,model_type,AE_loss_list,gene,count,fixed_x,toValidate,gene_data_valid_Tensor,skip_connection_mode,toPrintInfo=False, toMask=True):
criterionBCE = nn.BCELoss()
criterionMSE = nn.MSELoss()
for epoch in range(num_epochs):
print("Now epoch:%d"%epoch)
t0 = time()
for i_data_batch, [images,y_train_T_tensor] in enumerate(data_loader): # for i, (images, _) in enumerate(data_loader):
images = AE.to_var(images.view(images.size(0), -1)).float()
if toPrintInfo:
print("DEBUG INFO:before the input of model MeiNN")
print(images)
#y_pred_masked = y_pred
y_masked = y_train_T_tensor
out, y_pred_list, embedding = ae(images)
if toValidate:
valid_out, valid_y_pred_list, valid_embedding = ae(gene_data_valid_Tensor.T) # for validation
y_masked = y_train_T_tensor[:, task_idx:task_idx+1]
if toMask:
mask = y_masked.ne(0.5)
# Move mask and y_masked to the same device as y_pred_list[task_idx]
mask = mask.to(y_pred_list[task_idx].device)
y_masked = y_masked.to(y_pred_list[task_idx].device)
y_masked = y_masked * mask
y_pred_masked = y_pred_list[task_idx] * mask
reg_loss = return_reg_loss(ae)
print("="*100)
print("y_pred_masked")
print(y_pred_masked)
print("y_masked")