-
Notifications
You must be signed in to change notification settings - Fork 8
/
concerto_function5_3.py
2297 lines (2008 loc) · 108 KB
/
concerto_function5_3.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
import tensorflow as tf
import numpy as np
import os
import scanpy as sc
import argparse
import pandas as pd
import copy
from collections import Counter
from scipy.sparse import issparse
import scipy
import sys
#sys.path.append("./Concerto-main/")
from bgi.utils.data_utils import *
from bgi.models.DeepSingleCell import *
from bgi.metrics.clustering_metrics import *
from bgi.losses.contrastive_loss import simclr_loss
import re
import h5py
import time
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
#return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value.encode()]))
def _float_feature(value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=list(value)))
def _int64_feature(value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=list(value)))
def set_seeds(seed=10):
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
tf.random.set_seed(seed)
np.random.seed(seed)
def preprocessing_rna(
adata,
min_features: int = 600,
min_cells: int = 3,
target_sum: int = 10000,
n_top_features=2000, # or gene list
chunk_size: int = 20000,
is_hvg = False,
batch_key = 'batch',
log=True
):
if min_features is None: min_features = 600
if n_top_features is None: n_top_features = 40000
if not issparse(adata.X):
adata.X = scipy.sparse.csr_matrix(adata.X)
# adata = adata[:, [gene for gene in adata.var_names
# if not str(gene).startswith(tuple(['ERCC', 'MT-', 'mt-']))]]
sc.pp.filter_cells(adata, min_genes=min_features)
#sc.pp.filter_genes(adata, min_cells=min_cells)
sc.pp.normalize_total(adata, target_sum=target_sum)
sc.pp.log1p(adata)
if is_hvg == True:
sc.pp.highly_variable_genes(adata, n_top_genes=n_top_features, batch_key=batch_key, inplace=False, subset=True)
print('Processed dataset shape: {}'.format(adata.shape))
return adata
def serialize_example_batch(x_feature, x_weight, y_batch,x_id):
feature = {
'feature': _int64_feature(x_feature),
'value': _float_feature(x_weight),
'batch': _int64_feature(y_batch),
'id': _bytes_feature(x_id)
}
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
return example_proto.SerializeToString()
def create_tfrecord(source_file, batch_dict, tfrecord_file, zero_filter=False, norm=False, batch_key = 'batch'):
if type(source_file.X) != np.ndarray:
x_data = source_file.X.toarray()
else:
x_data = source_file.X
batch_data = source_file.obs[batch_key].tolist()
obs_name_list = source_file.obs_names.tolist()
batch_number = []
for j in range(len(batch_data)):
batch = batch_data[j]
place = batch_dict.index(batch)
batch_number.append(place)
counter = 0
batch_examples = {}
for x, batch,k in zip(x_data, batch_number,obs_name_list):
if zero_filter is False:
x = x + 10e-6
indexes = np.where(x >= 0.0)
else:
indexes = np.where(x > 0.0)
values = x[indexes]
features = np.array(indexes)
features = np.reshape(features, (features.shape[1]))
values = np.array(values, dtype=np.float)
# values = values / np.linalg.norm(values)
if batch not in batch_examples:
batch_examples[batch] = []
example = serialize_example_batch(features, values, np.array([int(batch)]),k)
batch_examples[batch].append(example)
counter += 1
if counter % 1000 == 0:
print('counter: {} shape: {}, batch: {}'.format(counter, features.shape, batch))
#print(x)
#print(values)
#print("batchs: ", batch_dict)
for item in batch_examples.items():
batch = item[0]
examples = item[1]
if zero_filter is False:
file = tfrecord_file.replace('.tfrecord', '_{}.tfrecord'.format(batch))
else:
if norm is False:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero_no_norm.tfrecord'.format(batch))
else:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero.tfrecord'.format(batch))
with tf.io.TFRecordWriter(file) as writer:
for example in examples:
writer.write(example)
save_dict = {'vocab size': len(features)}
file = tfrecord_file.replace('tf.tfrecord','vocab_size.npz')
np.savez_compressed(file, **save_dict)
# np.savez_compressed('vocab_size.npz', **save_dict)
# 输入模块
def concerto_input(input_file_list):
query_adata = sc.read(input_file_list)
return query_adata
# 预处理模块
def concerto_preprocess(query_adata):
sc.pp.normalize_total(query_adata, target_sum=10000)
sc.pp.log1p(query_adata)
return query_adata
# 交集基因
def concerto_intersect_gene(ref_adata, query_adata, parameters=None):
ref_var_list = ref_adata.var_names.tolist()
query_var_list = query_adata.var_names.tolist()
intersect_gene_list = list(set(ref_var_list).intersection(set(query_var_list)))
intersect_stats_A_B = len(list(set(ref_var_list).difference(set(query_var_list))))# ref中有query中无的个数
intersect_stats_B_A = len(list(set(query_var_list).difference(set(ref_var_list)))) # ref中有query中无的个数
intersect_stats = [intersect_stats_A_B,len(intersect_gene_list),intersect_stats_B_A]
return intersect_gene_list, intersect_stats # list, [int, int, int]([A-B, A交B, B-A])
# HVG
def concerto_HVG(ref_adata,query_adata,n_top_genes=None, min_disp=0.5, min_mean=0.0125, max_mean=3,
parameters=None):
sc.pp.highly_variable_genes(query_adata, n_top_genes=n_top_genes, min_disp=0.5,min_mean=0.0125, max_mean=3)
sc.pp.highly_variable_genes(ref_adata, n_top_genes=n_top_genes, min_disp=0.5, min_mean=0.0125, max_mean=3)
ref_adata = ref_adata[:,ref_adata.var.highly_variable]
query_adata = query_adata[:,query_adata.var.highly_variable]
HVG_list = list(set(ref_adata.var_names.tolist()).intersection(set(query_adata.var_names.tolist())))
processed_query_adata = query_adata[:,HVG_list]
processed_ref_adata = ref_adata[:, HVG_list]
return processed_ref_adata, processed_query_adata, HVG_list
# 如果不训新模型,补全到Ref的基因个数
def concerto_padding(ref_gene_list_path:str, ref_weight_path:str, query_adata):
# 检验 ref gene list和 weight size 一致
f = h5py.File(ref_weight_path, 'r') # 打开h5文件
if 'RNA-Embedding/embeddings:0' in f['RNA-Embedding']:
weight_size = f['RNA-Embedding']['RNA-Embedding/embeddings:0'].value.shape[0]
print('unsup model')
else:
weight_size = f['RNA-Embedding']['RNA-Embedding_1/embeddings:0'].value.shape[0]
print('sup model')
gene_names = list(pd.read_csv(ref_gene_list_path)['0'].values)
if weight_size == len(gene_names):
query_gene_list = query_adata.var_names.tolist()
gene_inter_list = list(set(gene_names).intersection(set(query_gene_list)))
empty_matrix = np.zeros([len(query_adata.obs_names),len(gene_names)])
inter_index = []
inter_index_query = []
for i in gene_inter_list:
inter_index.append(gene_names.index(i))
inter_index_query.append(query_gene_list.index(i))
query_X = query_adata.X.toarray()
query_X_inter = query_X[:, inter_index_query]
for j in range(query_X_inter.shape[1]):
empty_matrix[:, inter_index[j]] = query_X_inter[:, j]
q = sc.AnnData(empty_matrix)
q.obs = query_adata.obs.copy()
q.var_names = gene_names
return q
else:
return print('weight size is different from ref gene list')
def concerto_padding2(ref_gene_list_path:str, ref_weight_path:str, query_adata):
gene_names = list(pd.read_csv(ref_gene_list_path)['0'].values)
query_gene_list = query_adata.var_names.tolist()
gene_inter_list = list(set(gene_names).intersection(set(query_gene_list)))
empty_matrix = np.zeros([len(query_adata.obs_names),len(gene_names)])
inter_index = []
inter_index_query = []
for i in gene_inter_list:
inter_index.append(gene_names.index(i))
inter_index_query.append(query_gene_list.index(i))
query_X = query_adata.X.toarray()
query_X_inter = query_X[:, inter_index_query]
for j in range(query_X_inter.shape[1]):
empty_matrix[:, inter_index[j]] = query_X_inter[:, j]
q = sc.AnnData(empty_matrix)
q.obs = query_adata.obs.copy()
q.var_names = gene_names
return q
# 造tfrecords
def concerto_make_tfrecord(processed_ref_adata, tf_path, batch_col_name=None):
# 有输入batch_col_name的时候,用这列作为batchid, 若无假设所有是一个batch
# 不做乱序,
if batch_col_name is None:
batch_col_name = 'batch_'
sample_num = len(processed_ref_adata.obs_names.tolist())
processed_ref_adata.obs[batch_col_name] = ['0']*sample_num
print(processed_ref_adata)
batch_list = processed_ref_adata.obs[batch_col_name].unique().tolist()
cc = dict(Counter(batch_list))
cc = list(cc.keys())
tfrecord_file = tf_path + '/tf.tfrecord'
if not os.path.exists(tf_path):
os.makedirs(tf_path)
create_tfrecord(processed_ref_adata, cc, tfrecord_file, zero_filter=False, norm=True, batch_key =batch_col_name)
return tf_path
# ---------- make supervised tfr --------------
def serialize_example_batch_supervised(x_feature, x_weight, y_label,y_batch,x_id):
feature = {
'feature': _int64_feature(x_feature),
'value': _float_feature(x_weight),
'label': _int64_feature(y_label),
'batch': _int64_feature(y_batch),
'id': _bytes_feature(x_id)
}
example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
return example_proto.SerializeToString()
def create_tfrecord_supervised(source_file, batch_dict,label_dict, tfrecord_file, zero_filter=False, norm=False, batch_key = 'batch',label_key = 'label'):
if type(source_file.X) != np.ndarray:
x_data = source_file.X.toarray()
else:
x_data = source_file.X
batch_data = source_file.obs[batch_key].tolist()
label_data = source_file.obs[label_key].tolist()
obs_name_list = source_file.obs_names.tolist()
batch_number = []
label_number = []
for j in range(len(batch_data)):
batch = batch_data[j]
place = batch_dict.index(batch)
batch_number.append(place)
for j in range(len(label_data)):
cell_type = label_data[j]
place = label_dict.index(cell_type)
label_number.append(place)
counter = 0
batch_examples = {}
for x, y,batch,k in zip(x_data, label_number,batch_number,obs_name_list):
if zero_filter is False:
x = x + 10e-6
indexes = np.where(x >= 0.0)
else:
indexes = np.where(x > 0.0)
values = x[indexes]
features = np.array(indexes)
features = np.reshape(features, (features.shape[1]))
values = np.array(values, dtype=np.float)
# values = values / np.linalg.norm(values)
if batch not in batch_examples:
batch_examples[batch] = []
y = np.array([int(y)])
example = serialize_example_batch_supervised(features, values, y, np.array([int(batch)]),k)
batch_examples[batch].append(example)
counter += 1
if counter % 100 == 0:
print('counter: {} shape: {}, batch: {}'.format(counter, features.shape, batch))
print(x)
print(values)
print("batchs: ", batch_dict)
for item in batch_examples.items():
batch = item[0]
examples = item[1]
if zero_filter is False:
file = tfrecord_file.replace('.tfrecord', '_{}.tfrecord'.format(batch))
else:
if norm is False:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero_no_norm.tfrecord'.format(batch))
else:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero.tfrecord'.format(batch))
with tf.io.TFRecordWriter(file) as writer:
for example in examples:
writer.write(example)
#save_dict = {'vocab size': len(features)}
save_dict = {'vocab size': len(features),'classes number':len(label_dict),'label_dict':label_dict,'batch_dict':batch_dict}
file = tfrecord_file.replace('tf.tfrecord','vocab_size.npz')
np.savez_compressed(file, **save_dict)
# 造tfrecords
def concerto_make_tfrecord_supervised(processed_ref_adata, tf_path,save_dict = None, batch_col_name=None,label_col_name=None):
# 有输入batch_col_name的时候,用这列作为batchid, 若无假设所有是一个batch
# 不做乱序,
tfrecord_file = os.path.join(tf_path, 'tf.tfrecord')
if not os.path.exists(tf_path):
os.makedirs(tf_path)
if batch_col_name is None:
batch_col_name = 'batch'
sample_num = len(processed_ref_adata.obs_names.tolist())
processed_ref_adata.obs[batch_col_name] = ['0'] * sample_num
if label_col_name is None:
label_col_name = 'label'
if save_dict is not None:
f = np.load(os.path.join(save_dict,'vocab_size.npz')) # load saved dict path
cc_ = list(f['label_dict'])
cc = list(f['batch_dict'])
else:
batch_list = processed_ref_adata.obs[batch_col_name].unique().tolist()
cc = dict(Counter(batch_list))
cc = list(cc.keys())
label_list = processed_ref_adata.obs[label_col_name].unique().tolist()
cc_ = dict(Counter(label_list))
cc_ = list(cc_.keys())
create_tfrecord_supervised(processed_ref_adata, cc,cc_, tfrecord_file, zero_filter=False, norm=True, batch_key =batch_col_name,label_key=label_col_name)
return tf_path
def create_tfrecord_supervised_1batch(source_file, batch_dict,label_dict, tfrecord_file, zero_filter=False, norm=False, batch_key = 'batch',label_key = 'label'):
if type(source_file.X) != np.ndarray:
x_data = source_file.X.toarray()
else:
x_data = source_file.X
batch_data = source_file.obs[batch_key].tolist()
label_data = source_file.obs[label_key].tolist()
obs_name_list = source_file.obs_names.tolist()
batch_name = batch_dict[0]
batch_number = []
label_number = []
for j in range(len(batch_data)):
batch = batch_data[j]
place = batch_dict.index(batch)
batch_number.append(place)
for j in range(len(label_data)):
cell_type = label_data[j]
place = label_dict.index(cell_type)
label_number.append(place)
counter = 0
batch_examples = {}
for x, y,batch,k in zip(x_data, label_number,batch_number,obs_name_list):
if zero_filter is False:
x = x + 10e-6
indexes = np.where(x >= 0.0)
else:
indexes = np.where(x > 0.0)
values = x[indexes]
features = np.array(indexes)
features = np.reshape(features, (features.shape[1]))
values = np.array(values, dtype=np.float)
# values = values / np.linalg.norm(values)
if batch not in batch_examples:
batch_examples[batch] = []
y = np.array([int(y)])
example = serialize_example_batch_supervised(features, values, y, np.array([int(batch)]),k)
batch_examples[batch].append(example)
counter += 1
if counter % 100 == 0:
print('counter: {} shape: {}, batch: {}'.format(counter, features.shape, batch))
print(x)
print(values)
print("batchs: ", batch_dict)
for item in batch_examples.items():
batch = item[0]
examples = item[1]
if zero_filter is False:
file = tfrecord_file.replace('.tfrecord', '_{}.tfrecord'.format(batch_name))
else:
if norm is False:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero_no_norm.tfrecord'.format(batch_name))
else:
file = tfrecord_file.replace('.tfrecord', '_{}_no_zero.tfrecord'.format(batch_name))
with tf.io.TFRecordWriter(file) as writer:
for example in examples:
writer.write(example)
#save_dict = {'vocab size': len(features)}
save_dict = {'vocab size': len(features),'classes number':len(label_dict),'label_dict':label_dict,'batch_dict':batch_dict}
file = tfrecord_file.replace('tf.tfrecord','vocab_size.npz')
np.savez_compressed(file, **save_dict)
# 造tfrecords
def concerto_make_tfrecord_supervised_1batch(processed_ref_adata, tf_path, save_dict = None, batch_col_name=None,label_col_name=None):
# 有输入batch_col_name的时候,用这列作为batchid, 若无假设所有是一个batch
# 不做乱序,
tfrecord_file = os.path.join(tf_path, 'tf.tfrecord')
if not os.path.exists(tf_path):
os.makedirs(tf_path)
if batch_col_name is None:
batch_col_name = 'batch'
sample_num = len(processed_ref_adata.obs_names.tolist())
processed_ref_adata.obs[batch_col_name] = ['0'] * sample_num
if label_col_name is None:
label_col_name = 'label'
if save_dict is not None:
f = np.load(os.path.join(save_dict,'vocab_size.npz')) # load saved dict path
cc_ = list(f['label_dict'])
cc = list(f['batch_dict'])
else:
batch_list = processed_ref_adata.obs[batch_col_name].unique().tolist()
cc = dict(Counter(batch_list))
cc = list(cc.keys())
label_list = processed_ref_adata.obs[label_col_name].unique().tolist()
cc_ = dict(Counter(label_list))
cc_ = list(cc_.keys())
create_tfrecord_supervised_1batch(processed_ref_adata, cc,cc_, tfrecord_file, zero_filter=False, norm=True, batch_key =batch_col_name,label_key=label_col_name)
return tf_path
# -----------make supervised tfr end-----------
# train unsupervised
def concerto_train_ref(ref_tf_path:str, weight_path:str, super_parameters=None):
set_seeds(0)
if not os.path.exists(weight_path):
os.makedirs(weight_path)
if super_parameters is None:
super_parameters = {'batch_size':32,'epoch':3,'lr':1e-5}
# dirname = os.getcwd()
# f = np.load(ref_tf_path + './vocab_size.npz')
f = np.load(os.path.join(ref_tf_path,'vocab_size.npz'))
vocab_size = int(f['vocab size'])
encode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=True,
drop_rate=0.1,
head_1=128,
head_2=128,
head_3=128)
decode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=False,
drop_rate=0.1,
head_1=128,
head_2=128,
head_3=128)
# tf_list_1 = os.listdir(os.path.join(ref_tf_path))
tf_list_1 = [f for f in os.listdir(os.path.join(ref_tf_path)) if 'tfrecord' in f]
train_source_list = []
for i in tf_list_1:
train_source_list.append(os.path.join(ref_tf_path, i))
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_cls_accuracy')
test_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_cls_accuracy')
total_update_steps = 300 * super_parameters['epoch']
lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(super_parameters['lr'], total_update_steps, super_parameters['lr']*1e-2, power=1)
opt_simclr = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
for epoch in range(super_parameters['epoch']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
z1 = encode_network([source_features, source_values], training=True)
z2 = decode_network([source_values], training=True)
ssl_loss = simclr_loss(z1, z2,temperature = 0.1)
loss = ssl_loss
train_loss(loss)
variables = [encode_network.trainable_variables,
decode_network.trainable_variables,
]
grads = tape.gradient(loss, variables)
for grad, var in zip(grads, variables):
opt_simclr.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, simclr loss: {:0.4f}.'
print(template.format(epoch + 1,
str(step),
train_loss.result()))
encode_network.save_weights(
weight_path + 'weight_encoder_epoch{}.h5'.format(str(epoch+1)))
decode_network.save_weights(
weight_path + 'weight_decoder_epoch{}.h5'.format(str(epoch+1)))
return weight_path
# train supervised
# train
def concerto_train_ref_supervised(ref_tf_path:str, weight_path:str, super_parameters=None):
if not os.path.exists(weight_path):
os.makedirs(weight_path)
if super_parameters is None:
super_parameters = {'batch_size':32,'epoch_pretrain':1,'epoch_classifier':5,'lr':1e-5,}
# dirname = os.getcwd()
f = np.load(os.path.join(ref_tf_path, 'vocab_size.npz'))
vocab_size = int(f['vocab size'])
num_classes = int(f['classes number'])
encode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=True,
drop_rate=0.1,
head_1=128,
head_2=128,
head_3=128)
decode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=False,
drop_rate=0.1,
head_1=128,
head_2=128,
head_3=128)
# tf_list_1 = os.listdir(os.path.join(ref_tf_path))
tf_list_1 = [f for f in os.listdir(os.path.join(ref_tf_path)) if 'tfrecord' in f]
train_source_list = []
for i in tf_list_1:
train_source_list.append(os.path.join(ref_tf_path, i))
train_loss = tf.keras.metrics.Mean(name='train_loss')
cls_loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
train_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_cls_accuracy')
test_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_cls_accuracy')
total_update_steps = 300 * super_parameters['epoch_pretrain']
lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(super_parameters['lr'], total_update_steps, super_parameters['lr']*1e-2, power=1)
opt_simclr = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
for epoch in range(super_parameters['epoch_pretrain']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_label, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
z1 = encode_network([source_features, source_values], training=True)
z2 = decode_network([source_values], training=True)
ssl_loss = simclr_loss(z1, z2,temperature = 0.1)
loss = ssl_loss
train_loss(loss)
variables = [encode_network.trainable_variables,
decode_network.trainable_variables,
]
grads = tape.gradient(loss, variables)
for grad, var in zip(grads, variables):
opt_simclr.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, simclr loss: {:0.4f}.'
print(template.format(epoch + 1,
str(step),
train_loss.result()))
opt = tf.keras.optimizers.Adam(learning_rate=1e-3)
output = encode_network.layers[-1].output
output = tf.keras.layers.Dense(num_classes, activation='softmax', name='CLS')(output)
cls_network = tf.keras.Model(encode_network.input, outputs=output)
for epoch in range(super_parameters['epoch_classifier']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_label, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
outputs = cls_network([source_features, source_values], training=True)
classifer_loss = cls_loss_object(source_label, outputs)
source_pred = outputs
train_cls_accuracy(source_label, source_pred)
train_loss(classifer_loss)
variables = [cls_network.trainable_variables]
grads = tape.gradient(classifer_loss, variables)
for grad, var in zip(grads, variables):
opt.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, train cls loss: {:0.4f}, train acc: {:0.4f}'
print(template.format(epoch,
str(step),
train_loss.result(),
train_cls_accuracy.result(),
))
encode_network.save_weights(
os.path.join(weight_path, 'weight_encoder_epoch{}.h5'.format(str(epoch+1))))
decode_network.save_weights(
os.path.join(weight_path, 'weight_decoder_epoch{}.h5'.format(str(epoch+1))))
return weight_path
# train sup 0112
def concerto_train_ref_supervised_yzs(ref_tf_path:str, weight_path:str, super_parameters=None):
if not os.path.exists(weight_path):
os.makedirs(weight_path)
if super_parameters is None:
super_parameters = {'batch_size':32,'epoch_pretrain':1,'epoch_classifier':5,'lr':1e-5, 'drop_rate': 0.1}
# dirname = os.getcwd()
f = np.load(ref_tf_path + '/vocab_size.npz')
vocab_size = int(f['vocab size'])
num_classes = int(f['classes number'])
encode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=True,
drop_rate=super_parameters['drop_rate'],
head_1=128,
head_2=128,
head_3=128)
decode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=False,
drop_rate=super_parameters['drop_rate'],
head_1=128,
head_2=128,
head_3=128)
# tf_list_1 = os.listdir(os.path.join(ref_tf_path))
tf_list_1 = [f for f in os.listdir(os.path.join(ref_tf_path)) if 'tfrecord' in f]
train_source_list = []
for i in tf_list_1:
train_source_list.append(os.path.join(ref_tf_path, i))
train_loss = tf.keras.metrics.Mean(name='train_loss')
cls_loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
train_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_cls_accuracy')
test_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_cls_accuracy')
total_update_steps = 300 * super_parameters['epoch_pretrain']
lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(super_parameters['lr'], total_update_steps, super_parameters['lr']*1e-2, power=1)
opt_simclr = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
for epoch in range(super_parameters['epoch_pretrain']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_label, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
z1 = encode_network([source_features, source_values], training=True)
z2 = decode_network([source_values], training=True)
ssl_loss = simclr_loss(z1, z2,temperature = 0.1)
loss = ssl_loss
train_loss(loss)
variables = [encode_network.trainable_variables,
decode_network.trainable_variables,
]
grads = tape.gradient(loss, variables)
for grad, var in zip(grads, variables):
opt_simclr.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, simclr loss: {:0.4f}.'
print(template.format(epoch + 1,
str(step),
train_loss.result()))
opt = tf.keras.optimizers.Adam(learning_rate=1e-3)
output = encode_network.layers[-1].output
output = tf.keras.layers.Dense(num_classes, activation='softmax', name='CLS')(output)
cls_network = tf.keras.Model(encode_network.input, outputs=output)
for epoch in range(super_parameters['epoch_classifier']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_label, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
outputs = cls_network([source_features, source_values], training=True)
classifer_loss = cls_loss_object(source_label, outputs)
source_pred = outputs
train_cls_accuracy(source_label, source_pred)
train_loss(classifer_loss)
variables = [cls_network.trainable_variables]
grads = tape.gradient(classifer_loss, variables)
for grad, var in zip(grads, variables):
opt.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, train cls loss: {:0.4f}, train acc: {:0.4f}'
print(template.format(epoch,
str(step),
train_loss.result(),
train_cls_accuracy.result(),
))
encode_network.save_weights(
weight_path + 'weight_encoder_epoch{}.h5'.format(str(epoch+1)))
decode_network.save_weights(
weight_path + 'weight_decoder_epoch{}.h5'.format(str(epoch+1)))
cls_network.save_weights(os.path.join(weight_path, 'weight_cls_epoch{}.h5'.format(str(epoch+1))))
return weight_path
def concerto_train_inter_supervised_uda(ref_tf_path: str, weight_path: str,tissue_id: int, super_parameters=None):
def get_l2_loss(variables, excluded_keywords=None):
"""Traverse `tf.trainable_variables` compute L2 reg. Ignore `batch_norm`."""
def _is_excluded(v):
"""Guess whether a variable belongs to `batch_norm`."""
keywords = ['batchnorm', 'batch_norm', 'bn',
'layernorm', 'layer_norm']
if excluded_keywords is not None:
keywords += excluded_keywords
return any([k in v.name.lower() for k in keywords])
l2_losses = [tf.nn.l2_loss(v) for v in variables if not _is_excluded(v)]
return tf.add_n(l2_losses)
if not os.path.exists(weight_path):
os.makedirs(weight_path)
if super_parameters is None:
super_parameters = {'batch_size': 32, 'epoch_pretrain': 1, 'epoch_classifier': 5, 'lr': 1e-5, 'drop_rate': 0.1}
# dirname = os.getcwd()
f = np.load(ref_tf_path + '/vocab_size.npz')
vocab_size = int(f['vocab size'])
num_classes = int(f['classes number'])
encode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=True,
drop_rate=super_parameters['drop_rate'],
head_1=128,
head_2=128,
head_3=128)
decode_network = multi_embedding_attention_transfer(multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=False,
drop_rate=super_parameters['drop_rate'],
head_1=128,
head_2=128,
head_3=128)
# tf_list_1 = os.listdir(os.path.join(ref_tf_path))
tf_list_1 = [f for f in os.listdir(os.path.join(ref_tf_path)) if 'tfrecord' in f]
tf_list_1.remove('tf_{}.tfrecord'.format(tissue_id))
print('tf_list:',tf_list_1)
train_source_list = []
for i in tf_list_1:
train_source_list.append(os.path.join(ref_tf_path, i))
valid_files = os.path.join(ref_tf_path, 'tf_{}.tfrecord'.format(tissue_id))
print('valid_files path:',valid_files)
train_loss = tf.keras.metrics.Mean(name='train_loss')
cls_loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
train_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_cls_accuracy')
test_cls_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_cls_accuracy')
total_update_steps = 300 * super_parameters['epoch_pretrain']
lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay(super_parameters['lr'], total_update_steps,
super_parameters['lr'] * 1e-2, power=1)
opt_simclr = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
for epoch in range(super_parameters['epoch_pretrain']):
np.random.shuffle(train_source_list)
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
for step, (source_features, source_values, source_label, source_batch, source_id) in enumerate(train_db):
# enumerate
with tf.GradientTape() as tape:
z1 = encode_network([source_features, source_values], training=True)
z2 = decode_network([source_values], training=True)
ssl_loss = simclr_loss(z1, z2, temperature=0.1)
loss = ssl_loss
train_loss(loss)
variables = [encode_network.trainable_variables,
decode_network.trainable_variables,
]
grads = tape.gradient(loss, variables)
for grad, var in zip(grads, variables):
opt_simclr.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, simclr loss: {:0.4f}.'
print(template.format(epoch + 1,
str(step),
train_loss.result()))
opt = tf.keras.optimizers.Adam(learning_rate=1e-3)
output = encode_network.layers[-1].output
output = tf.keras.layers.Dense(num_classes, activation='softmax', name='CLS')(output)
output_decode = decode_network.layers[-1].output
output_decode = tf.keras.layers.Dense(num_classes, activation='softmax', name='CLS')(output_decode)
cls_network = tf.keras.Model(encode_network.input, outputs=output)
cls_network_1 = tf.keras.Model(decode_network.input, outputs=output_decode)
for epoch in range(super_parameters['epoch_classifier']):
np.random.shuffle(train_source_list)
valid_db = create_classifier_dataset_multi_supervised([valid_files],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
valid_db.repeat()
for file in train_source_list:
print(file)
train_db = create_classifier_dataset_multi_supervised([file],
batch_size=super_parameters['batch_size'],
is_training=True,
data_augment=False,
shuffle_size=10000)
train_loss.reset_states()
train_cls_accuracy.reset_states()
test_cls_accuracy.reset_states()
step = 0
for (source_features, source_values, source_label, source_batch, source_id), \
(target_features, target_values, target_label, target_batch, target_id) in (zip(train_db, valid_db)):
# enumerate
step += 1
with tf.GradientTape() as tape:
outputs = cls_network([source_features, source_values], training=True)
classifer_loss = cls_loss_object(source_label, outputs)
# UDA
uda_temp = 0.5
uda_threshold = 0.0
uda_data = 1
weight_decay = 1e-4
target_pred = cls_network([target_features, target_values], training=True)
aug_target_pred = cls_network_1(target_values, training=True)
target_labels = tf.nn.softmax(target_pred / uda_temp, axis=-1)
target_labels = tf.stop_gradient(target_labels)
target_cross_entropy = (target_labels * tf.nn.log_softmax(aug_target_pred, axis=-1))
largest_probs = tf.reduce_max(target_labels, axis=-1, keepdims=True)
masks_target = tf.greater_equal(largest_probs, uda_threshold)
masks_target = tf.cast(masks_target, tf.float32)
masks_target = tf.stop_gradient(masks_target)
target_cross_entropy = tf.reduce_mean(-target_cross_entropy * masks_target)
l2_reg_rate = tf.cast(weight_decay, tf.float32)
weight_dec = get_l2_loss(cls_network.trainable_variables)
total_loss = classifer_loss + target_cross_entropy + weight_dec * l2_reg_rate
source_pred = outputs
train_cls_accuracy(source_label, source_pred)
train_loss(total_loss)
variables = [cls_network.trainable_variables]
grads = tape.gradient(classifer_loss, variables)
for grad, var in zip(grads, variables):
opt.apply_gradients(zip(grad, var))
if step > 0 and step % 5 == 0:
template = 'Epoch {}, step {}, train cls loss: {:0.4f}, train acc: {:0.4f}'
print(template.format(epoch,
str(step),
train_loss.result(),
train_cls_accuracy.result(),
))
encode_network.save_weights(
weight_path + 'weight_encoder_epoch{}.h5'.format(str(epoch + 1)))
decode_network.save_weights(
weight_path + 'weight_decoder_epoch{}.h5'.format(str(epoch + 1)))
cls_network.save_weights(os.path.join(weight_path, 'weight_cls_epoch{}.h5'.format(str(epoch + 1))))
return weight_path
# test
def concerto_test_1set_attention_supervised(model_path: str, ref_tf_path: str, super_parameters=None, n_cells_for_ref=5000):
if super_parameters is None:
super_parameters = {'batch_size': 128, 'epoch': 1, 'lr': 1e-5,'drop_rate': 0.1}
f = np.load(os.path.join(ref_tf_path, 'vocab_size.npz'))
vocab_size = int(f['vocab size'])
num_classes = int(f['classes number'])
label_dict = f['label_dict']
batch_dict = f['batch_dict']
batch_size = super_parameters['batch_size']
encode_network = multi_embedding_attention_transfer(
multi_max_features=[vocab_size],
mult_feature_names=['RNA'],
embedding_dims=128,
include_attention=True,
drop_rate=super_parameters['drop_rate'],
head_1=128,
head_2=128,
head_3=128)
tf_list_1 = [f for f in os.listdir(os.path.join(ref_tf_path)) if 'tfrecord' in f]
train_source_list = [os.path.join(ref_tf_path, i) for i in tf_list_1]
# choose last epoch as test model
weight_id_list = []
# weight_list = [f for f in os.listdir(model_path) if (f.endswith('h5') and f.startswith('weight') )]
weight_list = [f for f in os.listdir(model_path) if (f.endswith('h5') and ('cls' in f))] # yyyx 1214
for id in weight_list: