forked from sidhomj/DeepTCR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentation.txt
More file actions
6097 lines (6084 loc) · 316 KB
/
Documentation.txt
File metadata and controls
6097 lines (6084 loc) · 316 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
Help on module DeepTCR:
NAME
DeepTCR
DESCRIPTION
# import sys
# sys.path.append('../')
# from DeepTCR.functions.Layers import *
# from DeepTCR.functions.utils_u import *
# from DeepTCR.functions.utils_s import *
# from DeepTCR.functions.act_fun import *
# from DeepTCR.functions.plot_func import *
# import seaborn as sns
# import colorsys
# from scipy.cluster.hierarchy import linkage,fcluster,dendrogram, leaves_list
# from scipy.stats import wasserstein_distance, entropy
# from scipy.spatial.distance import pdist, squareform
# import umap
# from sklearn.cluster import DBSCAN,KMeans
# import sklearn
# import DeepTCR.phenograph as phenograph
# from scipy.spatial import distance
# import glob
# from sklearn.preprocessing import LabelEncoder, OneHotEncoder, MultiLabelBinarizer
# from multiprocessing import Pool
# import pickle
# import matplotlib.pyplot as plt
# from sklearn.metrics import roc_curve, roc_auc_score
# import shutil
# import warnings
# from scipy.stats import spearmanr,gaussian_kde
CLASSES
builtins.object
DeepTCR_base
DeepTCR_S_base(DeepTCR_base, feature_analytics_class, vis_class)
DeepTCR_SS
DeepTCR_WF
DeepTCR_U(DeepTCR_base, feature_analytics_class, vis_class)
feature_analytics_class
vis_class
class DeepTCR_SS(DeepTCR_S_base)
| DeepTCR_SS(Name, max_length=40, device=0)
|
| Method resolution order:
| DeepTCR_SS
| DeepTCR_S_base
| DeepTCR_base
| feature_analytics_class
| vis_class
| builtins.object
|
| Methods defined here:
|
| Get_Train_Valid_Test(self, test_size=0.25, LOO=None, split_by_sample=False, combine_train_valid=False)
| Train/Valid/Test Splits.
|
| Divide data for train, valid, test set. Training is used to
| train model parameters, validation is used to set early stopping,
| and test acts as blackbox independent test set.
|
| Inputs
| ---------------------------------------
| test_size: float
| Fraction of sample to be used for valid and test set.
|
| LOO: int
| Number of sequences to leave-out in Leave-One-Out Cross-Validation. For example,
| when set to 20, 20 sequences will be left out for the validation set and 20 samples will be left
| out for the test set.
|
| split_by_sample: int
| In the case one wants to train the single sequence classifer but not to mix the train/test
| sets with sequences from different samples, one can set this parameter to True to do the train/test
| splits by sample.
|
| combine_train_valid: bool
| To combine the training and validation partitions into one which will be used for training
| and updating the model parameters, set this to True. This will also set the validation partition
| to the test partition. In other words, new train set becomes (original train + original valid) and then
| new valid = original test partition, new test = original test partition. Therefore, if setting this parameter
| to True, change one of the training parameters to set the stop training criterion (i.e. train_loss_min)
| to stop training based on the train set. If one does not chanage the stop training criterion, the decision of
| when to stop training will be based on the test data (which is considered a form of over-fitting).
|
| K_Fold_CrossVal(self, folds=None, split_by_sample=False, combine_train_valid=False, seeds=None, kernel=5, trainable_embedding=True, embedding_dim_aa=64, embedding_dim_genes=48, embedding_dim_hla=12, num_fc_layers=0, units_fc=12, weight_by_class=False, class_weights=None, use_only_seq=False, use_only_gene=False, use_only_hla=False, size_of_net='medium', graph_seed=None, drop_out_rate=0.0, multisample_dropout=False, multisample_dropout_rate=0.5, multisample_dropout_num_masks=64, batch_size=1000, epochs_min=10, stop_criterion=0.001, stop_criterion_window=10, accuracy_min=None, train_loss_min=None, hinge_loss_t=0.0, convergence='validation', learning_rate=0.001, suppress_output=False, batch_seed=None)
| K_Fold Cross-Validation for Single-Sequence Classifier
|
| If the number of sequences is small but training the single-sequence classifier, one
| can use K_Fold Cross Validation to train on all but one before assessing
| predictive performance.After this method is run, the AUC_Curve method can be run to
| assess the overall performance.
|
| Inputs
| ---------------------------------------
| K-Fold Parameters
|
| folds: int
| Number of Folds
|
| split_by_sample: int
| In the case one wants to train the single sequence classifer but not to mix the train/test
| sets with sequences from different samples, one can set this parameter to True to do the train/test
| splits by sample.
|
| combine_train_valid: bool
| To combine the training and validation partitions into one which will be used for training
| and updating the model parameters, set this to True. This will also set the validation partition
| to the test partition. In other words, new train set becomes (original train + original valid) and then
| new valid = original test partition, new test = original test partition. Therefore, if setting this parameter
| to True, change one of the training parameters to set the stop training criterion (i.e. train_loss_min)
| to stop training based on the train set. If one does not chanage the stop training criterion, the decision of
| when to stop training will be based on the test data (which is considered a form of over-fitting).
|
| seeds: nd.array
| In order to set a deterministic train/test split over the K-Fold Simulations, one can provide an array
| of seeds for each K-fold simulation. This will result in the same train/test split over the N Fold simulations.
| This parameter, if provided, should have the same size of the value of folds.
|
| Model Parameters
|
| kernel: int
| Size of convolutional kernel for first layer of convolutions.
|
| trainable_embedding; bool
| Toggle to control whether a trainable embedding layer is used or native
| one-hot representation for convolutional layers.
|
| embedding_dim_aa: int
| Learned latent dimensionality of amino-acids.
|
| embedding_dim_genes: int
| Learned latent dimensionality of VDJ genes
|
| embedding_dim_hla: int
| Learned latent dimensionality of HLA
|
| num_fc_layers: int
| Number of fully connected layers following convolutional layer.
|
| units_fc: int
| Number of nodes per fully-connected layers following convolutional layer.
|
| weight_by_class: bool
| Option to weight loss by the inverse of the class frequency. Useful for
| unbalanced classes.
|
| class_weights: dict
| In order to specify custom weights for each class during training, one
| can provide a dictionary with these weights.
| i.e. {'A':1.0,'B':2.0'}
|
| use_only_seq: bool
| To only use sequence feaures, set to True. This will turn off features learned
| from gene usage.
|
| use_only_gene: bool
| To only use gene-usage features, set to True. This will turn off features from
| the sequences.
|
| use_only_hla: bool
| To only use hla feaures, set to True.
|
| size_of_net: list or str
| The convolutional layers of this network have 3 layers for which the use can
| modify the number of neurons per layer. The user can either specify the size of the network
| with the following options:
| - small == [12,32,64] neurons for the 3 respective layers
| - medium == [32,64,128] neurons for the 3 respective layers
| - large == [64,128,256] neurons for the 3 respective layers
| - custom, where the user supplies a list with the number of nuerons for the respective layers
| i.e. [3,3,3] would have 3 neurons for all 3 layers.
| One can also adjust the number of layers for the convolutional stack by changing the length of
| this list. [3,3,3] = 3 layers, [3,3,3,3] = 4 layers.
|
| graph_seed: int
| For deterministic initialization of weights of the graph, set this to value of choice.
|
| drop_out_rate: float
| drop out rate for fully connected layers
|
| The following parameters are used to implement Multi-Sample Dropout at the final layer of the model as described in
| "Multi-Sample Dropout for Accelerated Training and Better Generalization"
| https://arxiv.org/abs/1905.09788
| This method has been shown to improve generalization of deep neural networks as well as inmprove convergence.
|
| multisample_dropout: bool
| Set this parameter to True to implement this method.
|
| multisample_dropout_rate: float
| The dropout rate for this multi-sample dropout layer.
|
| multisample_dropout_num_masks: int
| The number of masks to sample from for the Multi-Sample Dropout layer.
|
|
| Training Parameters
|
| batch_size: int
| Size of batch to be used for each training iteration of the net.
|
| epochs_min: int
| Minimum number of epochs for training neural network.
|
| stop_criterion: float
| Minimum percent decrease in determined interval (below) to continue
| training. Used as early stopping criterion.
|
| stop_criterion_window: int
| The window of data to apply the stopping criterion.
|
| accuracy_min: float
| Optional parameter to allow alternative training strategy until minimum
| training accuracy is achieved, at which point, training ceases.
|
| train_loss_min: float
| Optional parameter to allow alternative training strategy until minimum
| training loss is achieved, at which point, training ceases.
|
| hinge_loss_t: float
| The per sequence loss minimum at which the loss of that sequence is not used
| to penalize the model anymore. In other words, once a per sequence loss has hit
| this value, it gets set to 0.0.
|
| convergence: str
| This parameter determines which loss to assess the convergence criteria on.
| Options are 'validation' or 'training'. This is useful in the case one wants
| to change the convergence criteria on the training data when the training and validation
| partitions have been combined and used to training the model.
|
| learning_rate: float
| The learning rate for training the neural network. Making this value larger will
| increase the rate of convergence but can introduce instability into training. For most,
| altering this value will not be necessary.
|
| suppress_output: bool
| To suppress command line output with training statisitcs, set to True.
|
| batch_seed: int
| For deterministic batching during training, set this value to an integer of choice.
|
| Returns
| ---------------------------------------
|
| Monte_Carlo_CrossVal(self, folds=5, test_size=0.25, LOO=None, split_by_sample=False, combine_train_valid=False, seeds=None, kernel=5, trainable_embedding=True, embedding_dim_aa=64, embedding_dim_genes=48, embedding_dim_hla=12, num_fc_layers=0, units_fc=12, weight_by_class=False, class_weights=None, use_only_seq=False, use_only_gene=False, use_only_hla=False, size_of_net='medium', graph_seed=None, drop_out_rate=0.0, multisample_dropout=False, multisample_dropout_rate=0.5, multisample_dropout_num_masks=64, batch_size=1000, epochs_min=10, stop_criterion=0.001, stop_criterion_window=10, accuracy_min=None, train_loss_min=None, hinge_loss_t=0.0, convergence='validation', learning_rate=0.001, suppress_output=False, batch_seed=None)
| Monte Carlo Cross-Validation for Single-Sequence Classifier
|
| If the number of sequences is small but training the single-sequence classifier, one
| can use Monte Carlo Cross Validation to train a number of iterations before assessing
| predictive performance.After this method is run, the AUC_Curve method can be run to
| assess the overall performance.
|
| Inputs
| ---------------------------------------
| Monte-Carlo Parameters
|
| folds: int
| Number of iterations for Cross-Validation
|
| test_size: float
| Fraction of sample to be used for valid and test set.
|
| LOO: int
| Number of sequences to leave-out in Leave-One-Out Cross-Validation. For example,
| when set to 20, 20 sequences will be left out for the validation set and 20 samples will be left
| out for the test set.
|
| split_by_sample: int
| In the case one wants to train the single sequence classifer but not to mix the train/test
| sets with sequences from different samples, one can set this parameter to True to do the train/test
| splits by sample.
|
| combine_train_valid: bool
| To combine the training and validation partitions into one which will be used for training
| and updating the model parameters, set this to True. This will also set the validation partition
| to the test partition. In other words, new train set becomes (original train + original valid) and then
| new valid = original test partition, new test = original test partition. Therefore, if setting this parameter
| to True, change one of the training parameters to set the stop training criterion (i.e. train_loss_min)
| to stop training based on the train set. If one does not chanage the stop training criterion, the decision of
| when to stop training will be based on the test data (which is considered a form of over-fitting).
|
| seeds: nd.array
| In order to set a deterministic train/test split over the Monte-Carlo Simulations, one can provide an array
| of seeds for each MC simulation. This will result in the same train/test split over the N MC simulations.
| This parameter, if provided, should have the same size of the value of folds.
|
|
| Model Parameters
|
| kernel: int
| Size of convolutional kernel for first layer of convolutions.
|
| trainable_embedding; bool
| Toggle to control whether a trainable embedding layer is used or native
| one-hot representation for convolutional layers.
|
| embedding_dim_aa: int
| Learned latent dimensionality of amino-acids.
|
| embedding_dim_genes: int
| Learned latent dimensionality of VDJ genes
|
| embedding_dim_hla: int
| Learned latent dimensionality of HLA
|
| num_fc_layers: int
| Number of fully connected layers following convolutional layer.
|
| units_fc: int
| Number of nodes per fully-connected layers following convolutional layer.
|
| weight_by_class: bool
| Option to weight loss by the inverse of the class frequency. Useful for
| unbalanced classes.
|
| class_weights: dict
| In order to specify custom weights for each class during training, one
| can provide a dictionary with these weights.
| i.e. {'A':1.0,'B':2.0'}
|
| use_only_seq: bool
| To only use sequence feaures, set to True. This will turn off features learned
| from gene usage.
|
| use_only_gene: bool
| To only use gene-usage features, set to True. This will turn off features from
| the sequences.
|
| use_only_hla: bool
| To only use hla feaures, set to True.
|
| size_of_net: list or str
| The convolutional layers of this network have 3 layers for which the use can
| modify the number of neurons per layer. The user can either specify the size of the network
| with the following options:
| - small == [12,32,64] neurons for the 3 respective layers
| - medium == [32,64,128] neurons for the 3 respective layers
| - large == [64,128,256] neurons for the 3 respective layers
| - custom, where the user supplies a list with the number of nuerons for the respective layers
| i.e. [3,3,3] would have 3 neurons for all 3 layers.
| One can also adjust the number of layers for the convolutional stack by changing the length of
| this list. [3,3,3] = 3 layers, [3,3,3,3] = 4 layers.
|
| graph_seed: int
| For deterministic initialization of weights of the graph, set this to value of choice.
|
| drop_out_rate: float
| drop out rate for fully connected layers
|
| The following parameters are used to implement Multi-Sample Dropout at the final layer of the model as described in
| "Multi-Sample Dropout for Accelerated Training and Better Generalization"
| https://arxiv.org/abs/1905.09788
| This method has been shown to improve generalization of deep neural networks as well as inmprove convergence.
|
| multisample_dropout: bool
| Set this parameter to True to implement this method.
|
| multisample_dropout_rate: float
| The dropout rate for this multi-sample dropout layer.
|
| multisample_dropout_num_masks: int
| The number of masks to sample from for the Multi-Sample Dropout layer.
|
|
| Training Parameters
|
| batch_size: int
| Size of batch to be used for each training iteration of the net.
|
| epochs_min: int
| Minimum number of epochs for training neural network.
|
| stop_criterion: float
| Minimum percent decrease in determined interval (below) to continue
| training. Used as early stopping criterion.
|
| stop_criterion_window: int
| The window of data to apply the stopping criterion.
|
| accuracy_min: float
| Optional parameter to allow alternative training strategy until minimum
| training accuracy is achieved, at which point, training ceases.
|
| train_loss_min: float
| Optional parameter to allow alternative training strategy until minimum
| training loss is achieved, at which point, training ceases.
|
| hinge_loss_t: float
| The per sequence loss minimum at which the loss of that sequence is not used
| to penalize the model anymore. In other words, once a per sequence loss has hit
| this value, it gets set to 0.0.
|
| convergence: str
| This parameter determines which loss to assess the convergence criteria on.
| Options are 'validation' or 'training'. This is useful in the case one wants
| to change the convergence criteria on the training data when the training and validation
| partitions have been combined and used to training the model.
|
| learning_rate: float
| The learning rate for training the neural network. Making this value larger will
| increase the rate of convergence but can introduce instability into training. For most,
| altering this value will not be necessary.
|
| suppress_output: bool
| To suppress command line output with training statisitcs, set to True.
|
| batch_seed: int
| For deterministic batching during training, set this value to an integer of choice.
|
| Returns
| ---------------------------------------
|
| Train(self, kernel=5, trainable_embedding=True, embedding_dim_aa=64, embedding_dim_genes=48, embedding_dim_hla=12, num_fc_layers=0, units_fc=12, weight_by_class=False, class_weights=None, use_only_seq=False, use_only_gene=False, use_only_hla=False, size_of_net='medium', graph_seed=None, drop_out_rate=0.0, multisample_dropout=False, multisample_dropout_rate=0.5, multisample_dropout_num_masks=64, batch_size=1000, epochs_min=10, stop_criterion=0.001, stop_criterion_window=10, accuracy_min=None, train_loss_min=None, hinge_loss_t=0.0, convergence='validation', learning_rate=0.001, suppress_output=False, batch_seed=None)
| Train Single-Sequence Classifier
|
| This method trains the network and saves features values at the
| end of training for motif analysis.
|
| Inputs
| ---------------------------------------
| Model Parameters
|
| kernel: int
| Size of convolutional kernel for first layer of convolutions.
|
| trainable_embedding; bool
| Toggle to control whether a trainable embedding layer is used or native
| one-hot representation for convolutional layers.
|
| embedding_dim_aa: int
| Learned latent dimensionality of amino-acids.
|
| embedding_dim_genes: int
| Learned latent dimensionality of VDJ genes
|
| embedding_dim_hla: int
| Learned latent dimensionality of HLA
|
| num_fc_layers: int
| Number of fully connected layers following convolutional layer.
|
| units_fc: int
| Number of nodes per fully-connected layers following convolutional layer.
|
| weight_by_class: bool
| Option to weight loss by the inverse of the class frequency. Useful for
| unbalanced classes.
|
| class_weights: dict
| In order to specify custom weights for each class during training, one
| can provide a dictionary with these weights.
| i.e. {'A':1.0,'B':2.0'}
|
| use_only_seq: bool
| To only use sequence feaures, set to True. This will turn off features learned
| from gene usage.
|
| use_only_gene: bool
| To only use gene-usage features, set to True. This will turn off features from
| the sequences.
|
| use_only_hla: bool
| To only use hla feaures, set to True.
|
| size_of_net: list or str
| The convolutional layers of this network have 3 layers for which the use can
| modify the number of neurons per layer. The user can either specify the size of the network
| with the following options:
| - small == [12,32,64] neurons for the 3 respective layers
| - medium == [32,64,128] neurons for the 3 respective layers
| - large == [64,128,256] neurons for the 3 respective layers
| - custom, where the user supplies a list with the number of nuerons for the respective layers
| i.e. [3,3,3] would have 3 neurons for all 3 layers.
| One can also adjust the number of layers for the convolutional stack by changing the length of
| this list. [3,3,3] = 3 layers, [3,3,3,3] = 4 layers.
|
| graph_seed: int
| For deterministic initialization of weights of the graph, set this to value of choice.
|
| drop_out_rate: float
| drop out rate for fully connected layers
|
| The following parameters are used to implement Multi-Sample Dropout at the final layer of the model as described in
| "Multi-Sample Dropout for Accelerated Training and Better Generalization"
| https://arxiv.org/abs/1905.09788
| This method has been shown to improve generalization of deep neural networks as well as inmprove convergence.
|
| multisample_dropout: bool
| Set this parameter to True to implement this method.
|
| multisample_dropout_rate: float
| The dropout rate for this multi-sample dropout layer.
|
| multisample_dropout_num_masks: int
| The number of masks to sample from for the Multi-Sample Dropout layer.
|
|
| Training Parameters
|
| batch_size: int
| Size of batch to be used for each training iteration of the net.
|
| epochs_min: int
| Minimum number of epochs for training neural network.
|
| stop_criterion: float
| Minimum percent decrease in determined interval (below) to continue
| training. Used as early stopping criterion.
|
| stop_criterion_window: int
| The window of data to apply the stopping criterion.
|
| accuracy_min: float
| Optional parameter to allow alternative training strategy until minimum
| training accuracy is achieved, at which point, training ceases.
|
| train_loss_min: float
| Optional parameter to allow alternative training strategy until minimum
| training loss is achieved, at which point, training ceases.
|
| hinge_loss_t: float
| The per sequence loss minimum at which the loss of that sequence is not used
| to penalize the model anymore. In other words, once a per sequence loss has hit
| this value, it gets set to 0.0.
|
| convergence: str
| This parameter determines which loss to assess the convergence criteria on.
| Options are 'validation' or 'training'. This is useful in the case one wants
| to change the convergence criteria on the training data when the training and validation
| partitions have been combined and used to training the model.
|
| learning_rate: float
| The learning rate for training the neural network. Making this value larger will
| increase the rate of convergence but can introduce instability into training. For most,
| altering this value will not be necessary.
|
| suppress_output: bool
| To suppress command line output with training statisitcs, set to True.
|
| batch_seed: int
| For deterministic batching during training, set this value to an integer of choice.
|
| Returns
| ---------------------------------------
|
| ----------------------------------------------------------------------
| Methods inherited from DeepTCR_S_base:
|
| AUC_Curve(self, by=None, filename='AUC.tif', title=None, title_font=None, plot=True, diag_line=True, xtick_size=None, ytick_size=None, xlabel_size=None, ylabel_size=None, legend_font_size=None, frameon=True, legend_loc='lower right', figsize=None)
| AUC Curve for both Sequence and Repertoire/Sample Classifiers
|
| Inputs
| ---------------------------------------
| by: str
| To show AUC curve for only one class, set this parameter
| to the name of the class label one wants to plot.
|
| filename: str
| Filename to save tif file of AUC curve.
|
| title: str
| Optional Title to put on ROC Curve.
|
| title_font: int
| Optional font size for title
|
| plot: bool
| To suppress plotting and just save the data/figure, set to False.
|
| diag_line: bool
| To plot the line/diagonal of y=x defining no predictive power, set to True.
| To remove from plot, set to False.
|
| xtick_size: float
| Size of xticks
|
| ytick_size: float
| Size of yticks
|
| xlabel_size: float
| Size of xlabel
|
| ylabel_size: float
| Size of ylabel
|
| legend_font_size: float
| Size of legend
|
| frameon: bool
| Whether to show frame around legend.
|
| figsize: tuple
| To change the default size of the figure, set this to size of figure (i.e. - (10,10) )
|
| Returns
|
| self.AUC_DF: Pandas Dataframe
| AUC scores are returned for each class.
|
| In addition to plotting the ROC Curve, the AUC's are saved
| to a csv file in the results directory called 'AUC.csv'
|
| ---------------------------------------
|
| Representative_Sequences(self, top_seq=10, motif_seq=5, make_seq_logos=True, color_scheme='weblogo_protein', logo_file_format='.eps')
| Identify most highly predicted sequences for each class and corresponding motifs.
|
| This method allows the user to query which sequences were most predicted to belong to a given class along
| with the motifs that were learned for these representative sequences.
| Of note, this method only reports sequences that were in the test set so as not to return highly predicted
| sequences that were over-fit in the training set. To obtain the highest predicted sequences in all the data,
| run a K-fold cross-validation or Monte-Carlo cross-validation before running this method. In this way,
| the predicted probability will have been assigned to a sequence only when it was in the independent test set.
|
| In the case of a regression task, the representative sequences for the 'high' and 'low' values for the regression
| model are returned in the Rep_Seq Dict.
|
| This method will also determine motifs the network has learned that are highly associated with the label through
| multi-nomial linear regression and creates seq logos and fasta files in the results folder. Within a folder
| for a given class, the motifs are sorted by their linear coefficient. The coefficient is in the file name
| (i.e. 0_0.125_feature_2.eps reflects the the 0th highest feature with a coefficient of 0.125.
|
|
| Inputs
| ---------------------------------------
|
| top_seq: int
| The number of top sequences to show for each class.
|
| motif_seq: int
| The number of sequences to use to generate each motif. The more sequences, the possibly more noisy
| the seq_logo will be.
|
| make_seq_logos: bool
| In order to make seq logos for visualization of enriched motifs, set this to True. Whether this is set to
| True or not, the fast files that define enriched motifs will still be saved.
|
| color_scheme: str
| color scheme to use for LogoMaker.
| options are:
| weblogo_protein
| skylign_protein
| dmslogo_charge
| dmslogo_funcgroup
| hydrophobicity
| chemistry
| charge
| NajafabadiEtAl2017
|
| logo_file_format: str
| The type of image file one wants to save the seqlogo as. Default is vector-based format (.eps)
|
| Returns
|
| self.Rep_Seq: dictionary of dataframes
| This dictionary of dataframes holds for each class the top sequences and their respective
| probabiltiies for all classes. These dataframes can also be found in the results folder under Rep_Sequences.
|
| self.Rep_Seq_Features_(alpha/beta): dataframe
| This dataframe holds information for which features were associated by a multinomial linear model
| to the predicted probabilities of the neural network. The values in this dataframe are the linear model
| coefficients. This allows one to see which features were associated with the output of the trained
| neural network. These are also the same values that are on the motif seqlogo files in the results folder.
|
| Furthermore, the motifs are written in the results directory underneath the Motifs folder. To find the beta
| motifs for a given class, look under Motifs/beta/class_name/. These fasta/logo files are labeled by the linear
| coefficient of that given feature for that given class followed by the number name of the feature. These fasta files
| can then be visualized via weblogos at the following site: "https://weblogo.berkeley.edu/logo.cgi" or are present
| in the folder for direct visualization.
|
| ---------------------------------------
|
| Residue_Sensitivity_Logo(self, alpha_sequences=None, beta_sequences=None, v_beta=None, d_beta=None, j_beta=None, v_alpha=None, j_alpha=None, hla=None, p=None, batch_size=10000, models=None, figsize=(10, 8), low_color='red', medium_color='white', high_color='blue', font_name='serif', class_sel=None, cmap=None, min_size=0.0, edgecolor='black', edgewidth=0.25, background_color='white', Load_Prev_Data=False, norm_to_seq=True)
| Create Residue Sensitivity Logos
|
| This method allows the user to create Residue Sensitivity Logos where a set of provided sequences is perturbed
| to assess for position of the CDR3 sequence that if altered, would change the predicted specificity or affinity
| of the sequence (depending on whether training classification or regression task).
|
| Residue Sensitivity Logos can be created from any supervised model (including sequence and repertoire classifiers).
| Following the training of one of these models, one can feed into this method an cdr3 sequence defined by all/any
| of alpha/beta cdr3 sequence, V/D/J gene usage, and HLA context within which the TCR was seen.
|
| The output is a logo created by LogoMaker where the size of the character denotes how sensitive this position
| is to perturbation and color denotes the consequences of changes at this site. As default, red coloration means
| changes at this site would generally decrease the predicted value and blue coloration means changes at this site
| would increase the predicted value.
|
| Inputs
| ---------------------------------------
|
| alpha_sequences: ndarray of strings
| A 1d array with the sequences for inference for the alpha chain.
|
| beta_sequences: ndarray of strings
| A 1d array with the sequences for inference for the beta chain.
|
| v_beta: ndarray of strings
| A 1d array with the v-beta genes for inference.
|
| d_beta: ndarray of strings
| A 1d array with the d-beta genes for inference.
|
| j_beta: ndarray of strings
| A 1d array with the j-beta genes for inference.
|
| v_alpha: ndarray of strings
| A 1d array with the v-alpha genes for inference.
|
| j_alpha: ndarray of strings
| A 1d array with the j-alpha genes for inference.
|
| hla: ndarray of tuples/arrays
| To input the hla context for each sequence fed into DeepTCR, this will need to formatted
| as an ndarray that is (N,) for each sequence where each entry is a tuple/array of strings referring
| to the alleles seen for that sequence.
| ('A*01:01', 'A*11:01', 'B*35:01', 'B*35:02', 'C*04:01')
|
| p: multiprocessing pool object
| a pre-formed pool object can be passed to method for multiprocessing tasks.
|
| batch_size: int
| Batch size for inference.
|
| models: list
| In the case of the supervised sequence classifier, if several models were trained (via MC or Kfold crossvals),
| one can specify which ones to use for inference. Otherwise, thie method uses all trained models found in
| Name/models/ in an ensemble fashion. The method will output of the average of all models as well as the
| distribution of outputs for the user.
|
| figsize: tuple
| This specifies the dimensions of the logo.
|
| low_color: str
| The color to use when changes at this site would largely result in decreased prediction values.
|
| medium_color: str
| The color to use when changes at this site would result in either decreased or inreased prediction values.
|
| high_color: str
| The color to use when changes at this site would result in increased prediction values.
|
| font_name: str
| The font to use for LogoMaker.
|
| class_sel: str
| In the case of a model being trained in a multi-class fashion, one must select which class to make the
| logo for.
|
| cmap: matplotlib cmap
| One can alsp provide custom cmap for logomaker that will be used to denote changes at sites that result
| in increased of decreased prediction values.
|
| min_size: float (0.0 - 1.0)
| Some residues may have such little change with any perturbation that the character would be difficult to
| read. To set a minimum size for a residue, one can set this parameter to a value between 0 and 1.
|
| edgecolor: str
| The color of the edge of the characters of the logo.
|
| edgewidth: float
| The thickness of the edge of the characters.
|
| background_color: str
| The background color of the logo.
|
| norm_to_seq: bool
| When determining the color intensity of the logo, one can choose to normalize the value to just characters
| in that sequence (True) or one can choose to normalize to all characters in the sequences provdied (False).
|
| Load_Prev_Data: bool
| Since the first part of the method runs a time-intensive step to get all the predictions for all perturbations
| at all residue sites, we've incorporated a paramter which can be set to True following running the method once
| in order to adjust the visual aspects of the plot. Therefore, one should run this method first setting this parameter
| to False (it's default setting) but then switch to True and run again with different visualization parameters
| (i.e. figsize, etc).
|
| Returns
| ---------------------------------------
| (fig,ax) - the matplotlib figure and axis/axes.
|
| SRCC(self, s=10, kde=False, title=None)
| Spearman's Rank Correlation Coefficient Plot
|
| In the case one is doing a regression-based model for the sequence classiifer,
| one can plot the predicted vs actual labeled value with this method. The method
| returns a plot for the regression and a value of the correlation coefficient.
|
| Inputs
| ---------------------------------------
| s: int
| size of points for scatterplot
|
| kde: bool
| To do a kernel density estimation per point and plot this as a color-scheme,
| set to True. Warning: this option will take longer to run.
|
| title: str
| Title for the plot.
|
| Returns
| ---------------------------------------
| corr: float
| Spearman's Rank Correlation Coefficient
|
| ax: matplotlib axis
| axis on which plot is drawn
|
| ----------------------------------------------------------------------
| Methods inherited from DeepTCR_base:
|
| Get_Data(self, directory, Load_Prev_Data=False, classes=None, type_of_data_cut='Fraction_Response', data_cut=1.0, n_jobs=40, aa_column_alpha=None, aa_column_beta=None, count_column=None, sep='\t', aggregate_by_aa=True, v_alpha_column=None, j_alpha_column=None, v_beta_column=None, j_beta_column=None, d_beta_column=None, p=None, hla=None, use_hla_supertype=False, keep_non_supertype_alleles=False)
| Get Data for DeepTCR
|
| Parse Data into appropriate inputs for neural network from directories where data is stored.
|
| Inputs
| ---------------------------------------
| directory: str
| Path to directory with folders with tsv files are present
| for analysis. Folders names become labels for files within them. If the directory contains
| the TCRSeq files not organized into classes/labels, DeepTCR will load all files within that directory.
|
| Load_Prev_Data: bool
| Loads Previous Data.
|
| classes: list
| Optional selection of input of which sub-directories to use for analysis.
|
|
| type_of_data_cut: str
| Method by which one wants to sample from the TCRSeq File.
|
| Options are:
| Fraction_Response: A fraction (0 - 1) that samples the top fraction of the file by reads. For example,
| if one wants to sample the top 25% of reads, one would use this threshold with a data_cut = 0.25. The idea
| of this sampling is akin to sampling a fraction of cells from the file.
|
| Frequency_Cut: If one wants to select clones above a given frequency threshold, one would use this threshold.
| For example, if one wanted to only use clones about 1%, one would enter a data_cut value of 0.01.
|
| Num_Seq: If one wants to take the top N number of clones, one would use this threshold. For example,
| if one wanted to select the top 10 amino acid clones from each file, they would enter a data_cut value of 10.
|
| Read_Cut: If one wants to take amino acid clones with at least a certain number of reads, one would use
| this threshold. For example, if one wanted to only use clones with at least 10 reads,they would enter a data_cut value of 10.
|
| Read_Sum: IF one wants to take a given number of reads from each file, one would use this threshold. For example,
| if one wants to use the sequences comprising the top 100 reads of hte file, they would enter a data_cut value of 100.
|
| data_cut: float or int
| Value associated with type_of_data_cut parameter.
|
| n_jobs: int
| Number of processes to use for parallelized operations.
|
| aa_column_alpha: int
| Column where alpha chain amino acid data is stored. (0-indexed)
|
| aa_column_beta: int
| Column where beta chain amino acid data is stored.(0-indexed)
|
| count_column: int
| Column where counts are stored.
|
| sep: str
| Type of delimiter used in file with TCRSeq data.
|
| aggregate_by_aa: bool
| Choose to aggregate sequences by unique amino-acid. Defaults to True. If set to False, will allow duplicates
| of the same amino acid sequence given it comes from different nucleotide clones.
|
| v_alpha_column: int
| Column where v_alpha gene information is stored.
|
| j_alpha_column: int
| Column where j_alpha gene information is stored.
|
| v_beta_column: int
| Column where v_beta gene information is stored.
|
| d_beta_column: int
| Column where d_beta gene information is stored.
|
| j_beta_column: int
| Column where j_beta gene information is stored.
|
| p: multiprocessing pool object
| For parellelized operations, one can pass a multiprocessing pool object
| to this method.
|
| hla: str
| In order to use HLA information as part of the TCR-seq representation, one can provide
| a csv file where the first column is the file name and the remaining columns hold HLA alleles
| for each file. By including HLA information for each repertoire being analyzed, one is able to
| find a representation of TCR-Seq that is more meaningful across repertoires with different HLA
| backgrounds.
|
| use_hla_supertype: bool
| Given the diversity of the HLA-loci, training with a full allele may cause over-fitting. And while individuals
| may have different HLA alleles, these different allelees may bind peptide in a functionality similar way.
| This idea of supertypes of HLA is a method by which assignments of HLA genes can be aggregated to 6 HLA-A and
| 6 HLA-B supertypes. In roder to convert input of HLA-allele genes to supertypes, a more biologically functional
| representation, one can se this parameter to True and if the alleles provided are of one of 945 alleles found in
| the reference below, it will be assigned to a known supertype.
|
| For this method to work, alleles must be provided in the following format: A0101 where the first letter of the
| designation is the HLA loci (A or B) and then the 4 digit gene designation. HLA supertypes only exist for
| HLA-A and HLA-B. All other alleles will be dropped from the analysis.
|
| Sidney, J., Peters, B., Frahm, N., Brander, C., & Sette, A. (2008).
| HLA class I supertypes: a revised and updated classification. BMC immunology, 9(1), 1.
|
| keep_non_supertype_alleles: bool
| If assigning supertypes to HLA alleles, one can choose to keep HLA-alleles that do not have a known supertype
| (i.e. HLA-C alleles or certain HLA-A or HLA-B alleles) or discard them for the analysis. In order to keep these alleles,
| one should set this parameter to True. Default is False and non HLA-A or B alleles will be discarded.
|
| Returns
|
| self.alpha_sequences: ndarray
| array with alpha sequences (if provided)
|
| self.beta_sequences: ndarray
| array with beta sequences (if provided)
|
| self.class_id: ndarray
| array with sequence class labels
|
| self.sample_id: ndarray
| array with sequence file labels
|
| self.freq: ndarray
| array with sequence frequencies from samples
|
| self.counts: ndarray
| array with sequence counts from samples
|
| self.(v/d/j)_(alpha/beta): ndarray
| array with sequence (v/d/j)-(alpha/beta) usage
|
| ---------------------------------------
|
| Load_Data(self, alpha_sequences=None, beta_sequences=None, v_beta=None, d_beta=None, j_beta=None, v_alpha=None, j_alpha=None, class_labels=None, sample_labels=None, freq=None, counts=None, Y=None, p=None, hla=None, use_hla_supertype=False, keep_non_supertype_alleles=False, w=None)
| Load Data programatically into DeepTCR.
|
| DeepTCR allows direct user input of sequence data for DeepTCR analysis. By using this method,
| a user can load numpy arrays with relevant TCRSeq data for analysis.
|
| Inputs
| ---------------------------------------
|
| alpha_sequences: ndarray of strings
| A 1d array with the sequences for inference for the alpha chain.
|
| beta_sequences: ndarray of strings
| A 1d array with the sequences for inference for the beta chain.
|
| v_beta: ndarray of strings
| A 1d array with the v-beta genes for inference.
|
| d_beta: ndarray of strings
| A 1d array with the d-beta genes for inference.
|
| j_beta: ndarray of strings
| A 1d array with the j-beta genes for inference.
|
| v_alpha: ndarray of strings
| A 1d array with the v-alpha genes for inference.
|
| j_alpha: ndarray of strings
| A 1d array with the j-alpha genes for inference.
|
| class_labels: ndarray of strings
| A 1d array with class labels for the sequence (i.e. antigen-specificities)
|
| sample_labels: ndarray of strings
| A 1d array with sample labels for the sequence. (i.e. when loading data from different samples)
|
| counts: ndarray of ints
| A 1d array with the counts for each sequence, in the case they come from samples.
|
| freq: ndarray of float values
| A 1d array with the frequencies for each sequence, in the case they come from samples.
|
| Y: ndarray of float values
| In the case one wants to regress TCR sequences or repertoires against a numerical label, one can provide
| these numerical values for this input. For the TCR sequence regressor, each sequence will be regressed to
| the value denoted for each sequence. For the TCR repertoire regressor, the average of all instance level values
| will be used to regress the sample. Therefore, if there is one sample level value for regression, one would just
| repeat that same value for all the instances/sequences of the sample.
|
| hla: ndarray of tuples/arrays
| To input the hla context for each sequence fed into DeepTCR, this will need to formatted
| as an ndarray that is (N,) for each sequence where each entry is a tuple or array of strings referring
| to the alleles seen for that sequence.
| ('A*01:01', 'A*11:01', 'B*35:01', 'B*35:02', 'C*04:01')
|