-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3143 lines (2605 loc) · 129 KB
/
main.py
File metadata and controls
3143 lines (2605 loc) · 129 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
def main_data_processing():
"""
Script for loading the .fcs files of the datasets, perform data split on sample level,
apply transformation, subset to channels chosen for model training, save resulting data matrices to .npy files.
Additionally, save data from training and test samples respectively concatenated in one matrix.
Returns:
None
"""
import os
import copy
import re
import random
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from typing import List, Dict, Union, Tuple
from flagx.io import FlowDataManager
def data_processing_workflow(
dataset_names: List[str],
raw_data_paths: List[str],
data_file_types: List[str],
label_keys: List[str],
relabel_dicts: List[Union[Dict[int, int], None]],
cutoff_dicts: List[Union[Dict[str, int], None]],
data_splits: List[Union[Tuple[float, float], pd.DataFrame]],
channel_names: List[List[str]],
):
for dn, rdp, dft, lk, rd, cd, ds, cn, in zip(
dataset_names, raw_data_paths, data_file_types,
label_keys, relabel_dicts,
cutoff_dicts,
data_splits, channel_names,
):
for pf in ['arcsinh', 'log10'] :
# Set random seeds for random, numpy and torch
seed = 42
torch.manual_seed(seed) # Sets the seed for generating random numbers on all devices.
torch.cuda.manual_seed_all(seed) # Set the seed for generating random numbers on all GPUs.
# torch.cuda.manual_seed(seed) # Set the seed for generating random numbers for the current GPU.
# torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
# Set label key
current_lk = lk
# Define path where results should be stored and create dir
if pf == 'arcsinh':
pf_str = 'arcsinh_cofactor150'
else: # log10
if cd is not None:
pf_str = 'log10_w_custom_cutoffs'
else:
pf_str = 'log10_cutoff100'
np_data_p = os.path.join(
os.getcwd(),
f'data/np_files/{dn}/{pf_str}'
)
os.makedirs(os.path.join(np_data_p, 'data_handling'), exist_ok=True)
# ### Load and process the data set
# Create a list of the filenames
filename_list = sorted(os.listdir(rdp))
# Instantiate the FlowDataManager
fdm = FlowDataManager(
data_file_names=filename_list,
data_file_type=dft,
data_file_path=rdp,
save_path=os.path.join(np_data_p, 'data_handling'),
verbosity=2,
)
# Load data files to anndata
fdm.load_data_files_to_anndata()
# Check the number of events per sample
fdm.check_sample_sizes(filename_sample_sizes_df='sample_sizes.csv')
fdm.plot_sample_size_df(sample_size_df=fdm.sample_sizes_, dpi=300, ax=None)
plt.tight_layout()
plt.savefig(os.path.join(fdm.save_path, 'sample_sizes_df.png'))
# Align channel names
fdm.align_channel_names(
reference_channel_names=0, # Use 1st anndata in data list as reference
filename_log_df='og_channel_names.csv',
)
# Relabel data
if rd is not None:
new_label_key = 'new_labels'
fdm.relabel_data(
data_set='all',
old_to_new_label_mapping=rd,
label_key=current_lk,
label_layer_key=None, # No preprocessing done yet
new_label_key=new_label_key,
)
current_lk = new_label_key
# Apply sample wise preprocessing transformation
if pf == 'arcsinh':
prepr_kwargs = {'cofactor': 150}
else: # log10
if cd is not None: # If passed, apply channel wise cutoffs ...
pf = 'log10_w_custom_cutoffs'
prepr_kwargs = {
'cutoffs': cd,
}
else: # ... otherwise log10 with cutoff 100
pf = 'log10_w_cutoff'
prepr_kwargs = {'cutoff': 100}
fdm.sample_wise_preprocessing(flavour=pf, save_raw_to_layer='no_trafo', **prepr_kwargs)
# Split samples into train and test split (stratified for lymphoma datasets)
split_kwargs = {'shuffle': True, 'random_state': seed}
# Extract lymphoma subtype from filename for stratification
if dn not in {'imstat', 'flowcyt'}:
pattern = re.compile(r'^\d+_([A-Za-z]+)_')
lymphoma_subtypes = [pattern.search(f).group(1) for f in filename_list]
split_kwargs['stratify'] = lymphoma_subtypes
fdm.perform_data_split(
data_split=copy.deepcopy(ds),
filename_data_split='data_split.csv',
**split_kwargs
)
# Check class balance of train and test set
cb_df_train = fdm.check_class_balance(
data_set='train',
label_key=current_lk,
label_layer_key='no_trafo',
filename_class_balance_df='class_balance_train.csv',
)
fdm.plot_class_balance_df(class_balance_df=cb_df_train, dpi=300)
plt.savefig(os.path.join(fdm.save_path, 'class_balance_train.png'))
cb_df_test = fdm.check_class_balance(
data_set='test',
label_key=current_lk,
label_layer_key='no_trafo',
filename_class_balance_df='class_balance_test.csv',
)
fdm.plot_class_balance_df(class_balance_df=cb_df_test, dpi=300)
plt.savefig(os.path.join(fdm.save_path, 'class_balance_test.png'))
# Save data to numpy files
for sw in [False, True]:
for mode in ['train', 'test']:
dummy_save_path = os.path.join(np_data_p, '' if not sw else f'sample_wise_{mode}')
os.makedirs(dummy_save_path, exist_ok=True)
fdm.save_to_numpy_files(
data_set=mode,
sample_wise=sw,
save_path=dummy_save_path,
filename_suffix=f'_{mode}',
channels=cn,
layer_key=None, # Use adata.X, transformed data
label_key=current_lk,
label_layer_key='no_trafo', # Use labels from original untransformed data
shuffle=True, # Used pytorch dataloader under the hood, seed is set beforehand
precision='32bit', # Same as FCS
)
# ### Set flags and important variables ###########################################################################
# --- Immune status ---
ds_name_imstat = 'imstat'
raw_data_p_imstat = os.path.join(os.getcwd(), 'data/raw/imstat')
data_file_type_imstat = 'fcs'
data_split_imstat = pd.read_csv(
os.path.join(os.getcwd(), 'data/raw/imstat_data_split_development.csv'),
)
data_split_imstat['filename'] = data_split_imstat['filename'].apply(lambda x: f'{x}.fcs')
channels_imstat = ['FS INT', 'SS INT', '16-FITC', '56-PE', '3-ECD', '4-PC7', '19-APC', '14-APC700', '8-PB', '45-CO']
cutoff_dict_imstat = {
'FS INT': 100000, 'SS INT': 20000, '16-FITC': 250, '56-PE': 450, '3-ECD': 700,
'4-PC7': 1200,
'19-APC': 1700,
'14-APC700': 900,
'8-PB': 450, '45-CO': 500
}
label_key_imstat = 'population'
relabel_dict_imstat = None
# --- Lymphoma tube 1 ---
ds_name_lt1 = 'lymphoma_tube1'
raw_data_p_lt1 = os.path.join(
os.getcwd(),
'data/raw/lymphoma/concatenated_labled_fcs_format_21Blood4Bcell_T1_Labels'
)
data_file_type_lt1 = 'fcs'
data_split_lt1 = (0.6, 0.4)
channels_lt1 = [
'FS', 'SS', 'kappavCD8_FITC', 'lambdavCD7_PE', 'CD23_ECD', 'CD79bvCD4_PC5.5', 'CD5_PC7',
'CD38_APC', 'CD19_APC_A700', 'CD20vCD3_APC_A750', 'FMC7vCD2_PB', 'CD45_KrOr'
]
cutoff_dict_lt1 = {
'FS': 100000, 'SS': 20000, 'kappavCD8_FITC': 500, 'lambdavCD7_PE': 400, 'CD23_ECD': 500,
'CD79bvCD4_PC5.5': 1200, 'CD5_PC7': 300, 'CD38_APC': 700,
'CD19_APC_A700': 150,
'CD20vCD3_APC_A750': 500, 'FMC7vCD2_PB': 500, 'CD45_KrOr': 1000
}
label_key_lt1 = 'population'
relabel_dict_lt1 = None
# --- Lymphoma tube 1, binary case ---
ds_name_lt1_binary = 'lymphoma_tube1_binary'
raw_data_p_lt1_binary = raw_data_p_lt1
data_file_type_lt1_binary = data_file_type_lt1
data_split_lt1_binary = data_split_lt1
channels_lt1_binary = channels_lt1
cutoff_dict_lt1_binary = cutoff_dict_lt1
label_key_lt1_binary = label_key_lt1
relabel_dict_lt1_binary = {1: 1, 9: 1, 7: 0, 10: 0}
# Map:
# - class 1, 9 (B cells, B cells outside FSSS gate (dying B cells)) to label 1 (positive)
# - class 7, 10 (CD45 negative cells (mostly erythrocytes), other cells) to label 0 (negative)
# --- Lymphoma tube 2 ---
ds_name_lt2 = 'lymphoma_tube2'
raw_data_p_lt2 = os.path.join(
os.getcwd(),
'data/raw/lymphoma/concatenated_labled_fcs_format_22Blood4Bcell_T2_Labels'
)
data_file_type_lt2 = 'fcs'
data_split_lt2 = (0.6, 0.4)
channels_lt2 = [
'FS', 'SS', 'CD103_FITC', 'CD43_PE', 'CD25_ECD', 'CD10_PC5.5', 'CD200_PC7',
'CD52_APC', 'CD11c_APC_A700', 'CD20_APC_A750', 'IgM_PB', 'CD19_KrOr'
]
cutoff_dict_lt2 = {
'FS': 100000, 'SS': 20000, 'CD103_FITC': 300, 'CD43_PE': 1500, 'CD25_ECD': 1000,
'CD10_PC5.5': 1000, 'CD200_PC7': 1000, 'CD52_APC': 150, 'CD11c_APC_A700': 200,
'CD20_APC_A750': 300, 'IgM_PB': 400, 'CD19_KrOr': 200,
}
label_key_lt2 = 'population'
relabel_dict_lt2 = None
# --- Lymphoma tube 2, binary case ---
ds_name_lt2_binary = 'lymphoma_tube2_binary'
raw_data_p_lt2_binary = raw_data_p_lt2
data_file_type_lt2_binary = data_file_type_lt2
data_split_lt2_binary = data_split_lt2
channels_lt2_binary = channels_lt2
cutoff_dict_lt2_binary = cutoff_dict_lt2
label_key_lt2_binary = label_key_lt2
relabel_dict_lt2_binary = {1: 1, 9: 1, 7: 0, 10: 0}
# Map:
# - class 1, 9 (B cells, B cells outside FSSS gate (dying B cells)) to label 1 (positive)
# - class 7, 10 (CD45 negative cells (mostly erythrocytes), other cells) to label 0 (negative)
# --- Flowcyt ---
ds_name_flowcyt = 'flowcyt'
raw_data_p_flowcyt = os.path.join(os.getcwd(), 'data/raw/flowcyt/data_original')
data_file_type_flowcyt = 'csv'
data_split_flowcyt = (0.6, 0.4)
channels_flowcyt = [
'FS INT', 'SS INT', 'FL1 INT_CD14-FITC', 'FL2 INT_CD19-PE', 'FL3 INT_CD13-ECD', 'FL4 INT_CD33-PC5.5',
'FL5 INT_CD34-PC7', 'FL6 INT_CD117-APC', 'FL7 INT_CD7-APC700', 'FL8 INT_CD16-APC750', 'FL9 INT_HLA-PB',
'FL10 INT_CD45-KO'
]
cutoff_dict_flowcyt = None
label_key_flowcyt = 'label'
relabel_dict_flowcyt = None
# Define lists of parameters
dataset_names_input = [
ds_name_imstat,
ds_name_lt1, ds_name_lt2,
ds_name_lt1_binary, ds_name_lt2_binary,
ds_name_flowcyt
]
raw_data_paths_input = [
raw_data_p_imstat,
raw_data_p_lt1, raw_data_p_lt2,
raw_data_p_lt1_binary, raw_data_p_lt2_binary,
raw_data_p_flowcyt
]
data_file_types_input = [
data_file_type_imstat,
data_file_type_lt1, data_file_type_lt2,
data_file_type_lt1_binary, data_file_type_lt2_binary,
data_file_type_flowcyt
]
data_splits_input = [
data_split_imstat,
data_split_lt1, data_split_lt2,
data_split_lt1_binary, data_split_lt2_binary,
data_split_flowcyt
]
channel_names_input = [
channels_imstat,
channels_lt1, channels_lt2,
channels_lt1_binary, channels_lt2_binary,
channels_flowcyt
]
cutoff_dicts_input = [
cutoff_dict_imstat,
cutoff_dict_lt1, cutoff_dict_lt2,
cutoff_dict_lt1_binary, cutoff_dict_lt2_binary,
cutoff_dict_flowcyt
]
label_keys_input = [
label_key_imstat,
label_key_lt1, label_key_lt2,
label_key_lt1_binary, label_key_lt2_binary,
label_key_flowcyt
]
relabel_dicts_input = [
relabel_dict_imstat,
relabel_dict_lt1, relabel_dict_lt2,
relabel_dict_lt1_binary, relabel_dict_lt2_binary,
relabel_dict_flowcyt
]
data_processing_workflow(
dataset_names=dataset_names_input,
raw_data_paths=raw_data_paths_input,
data_file_types=data_file_types_input,
label_keys=label_keys_input,
relabel_dicts=relabel_dicts_input,
cutoff_dicts=cutoff_dicts_input,
data_splits=data_splits_input,
channel_names=channel_names_input,
)
def main_som_parameter_influence_study():
"""
Script for running parameter-wise hyperparameter tuning on the immune status dataset.
Its purpose is to determine the influence of individual parameters on the SOM classifier's performance
and get an intuition of the magnitude.
The workflow is as follows:
- Preprocessed data is loaded.
- Training data is downsampled to 10% of all events for faster training.
- 3-fold cross validation is performed.
- Results are saved and plotted.
Note: Analysis should be run for n_epochs first to set a sensible value for all other analyses.
The following flags are defined in the header and can be adjusted as needed:
- inference (bool), whether to do the training or just load and plot previously generated results.
- test_n_epochs (bool), whether to run analysis for n_epochs or all other parameters.
- random_seed (int)
- downsampling_frac (float)
- n_splits (int)
- n_epochs (int)
Returns:
None
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from flagx.gating import SomClassifier
from validation.plt import plot_param_lineplot, plot_param_stripplot
from validation.utils import set_pandas_print_options, get_downsampling_bool
# ### Set flags and variables ######################################################################################
inference = False # Whether to do the hyperparameter tuning or just view the results
test_n_epochs = False
random_seed = 42
downsampling_frac = 0.10
n_splits = 3
trafo = 'log10_w_custom_cutoffs'
# Based on gridsearch for n_epochs, selected n_epochs such that performance is stable with default parameters
n_epochs = 6000
####################################################################################################################
# ### Load the train data
data_p = os.path.join(os.getcwd(), f'data/np_files/imstat/{trafo}')
x = np.load(os.path.join(data_p, 'x_train.npy')).astype(np.float32)
y = np.load(os.path.join(data_p, 'y_train.npy')).astype(np.int32)
# ### Downsample for faster training
np.random.seed(random_seed)
target_num_events = int(x.shape[0] * downsampling_frac)
print((
f'# ### Downsampling training data from {x.shape[0]} events '
f'to {target_num_events} events ({int(downsampling_frac * 100)} %)'
))
downsampling_bool = get_downsampling_bool(y=y, target_num_events=target_num_events, stratified=True)
x = x[downsampling_bool, :]
y = y[downsampling_bool]
# ### Define parameter grids for each individual parameter
n_epochs_list = list(range(10, 101, 10)) + list(range(200, 1001, 100)) + list(range(2000, 15001, 1000))
param_grid_nepochs = {
'n_epochs': n_epochs_list,
}
param_grid_initialization = {
'initialization': ['random', 'pca'],
'n_epochs': [n_epochs, ],
}
param_grid_gridtype = {
'som_grid_type': ['rectangular', 'hexagonal'],
'n_epochs': [n_epochs, ],
}
param_grid_topology = {
'som_topology': ['planar', 'toroid'],
'n_epochs': [n_epochs, ],
}
param_grid_dimension = {
'som_dimensions': [(5, 5), (10, 10), (15, 15), (20, 20), (25, 25), (30, 30), (35, 35), (40, 40)],
'n_epochs': [n_epochs, ],
}
param_grid_neigh_fct = {
'neighborhood': ['gaussian', 'bubble'],
'n_epochs': [n_epochs, ],
}
param_grid_neigh_sigma = {
'gaussian_neighborhood_sigma': [0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0],
'n_epochs': [n_epochs, ],
}
param_grid_r0 = {
'radius_0': [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
# 0.0 => min(n_columns, n_rows)/2, rn_default = 1.0
'n_epochs': [n_epochs, ],
}
param_grid_rn = {
'radius_n': [4.0, 3.0, 2.0, 1.0, 0.75, 0.5, 0.25, 0.1, 0.01, 0.001],
# r0_default = min(n_columns, n_rows)/2 = 5
'n_epochs': [n_epochs, ],
}
param_grid_rcooling = {
'radius_cooling': ['linear', 'exponential'],
'n_epochs': [n_epochs, ],
}
param_grid_lr0 = {
'learning_rate_0': [0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 2.0],
# lr_n = 0.01 in default setting
'n_epochs': [n_epochs, ],
}
param_grid_lrn = {
'learning_rate_n': [0.1, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01, 0.005, 0.001],
# lr_0 = 0.1 in default setting
'n_epochs': [n_epochs, ],
}
param_grid_lrdecay = {
'learning_rate_decay': ['linear', 'exponential'],
'n_epochs': [n_epochs, ],
}
if test_n_epochs:
grids = [param_grid_nepochs, ]
grid_names = ['n_epochs', ]
else:
grids = [
param_grid_initialization,
param_grid_gridtype, param_grid_topology, param_grid_dimension,
param_grid_neigh_fct, param_grid_neigh_sigma, param_grid_r0, param_grid_rn, param_grid_rcooling,
param_grid_lr0, param_grid_lrn, param_grid_lrdecay
]
grid_names = [
'initialization',
'som_grid_type', 'som_topology', 'som_dimensions',
'neighborhood', 'gaussian_neighborhood_sigma', 'radius_0', 'radius_n', 'radius_cooling',
'learning_rate_0', 'learning_rate_n', 'learning_rate_decay'
]
# ### Perform the parameter tuning
# Define path where results will be stored
save_p = os.path.join(os.getcwd(), f'results/som_parameter_influence_study/{trafo}')
os.makedirs(save_p, exist_ok=True)
for grid, grid_name in zip(grids, grid_names):
print(f'# ### Grid name: {grid_name}')
current_save_p = os.path.join(save_p, grid_name)
os.makedirs(current_save_p, exist_ok=True)
if inference:
# Instantiate the SOM classifier
som_clf = SomClassifier(verbosity=2)
# Instantiate a stratified k-fold splitter
cv_splitter = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=random_seed)
# Perform cross-validated grid-search
som_clf.hyperparameter_tuning(
X=x.copy(),
y=y.copy(),
param_grid=grid,
cv=cv_splitter,
scoring='internal',
refit=False,
)
# Save SOM classifier with results
som_clf.save(filepath=current_save_p)
else:
# Load the previously trained SOM classifier
som_clf = SomClassifier.load(filepath=current_save_p)
# ### Evaluate the performance
res_df = pd.DataFrame(som_clf.grid_search_.cv_results_)
res_df.to_csv(os.path.join(current_save_p, f'{grid_name}.csv'))
set_pandas_print_options()
print('# ### Results:\n', res_df)
if grid_name in {
'initialization',
'som_grid_type', 'som_topology', 'som_dimensions',
'neighborhood', 'radius_cooling',
'learning_rate_decay'
}:
plot_param_stripplot(
res_df=res_df,
id_var='param_' + grid_name,
val_var= 'mean_test_score',
val_name='Macro F1',
jitter=True,
xlabel=grid_name,
dpi=300
)
plt.tight_layout()
plt.savefig(os.path.join(current_save_p, f'{grid_name}.png'))
plt.close('all')
else:
plot_param_lineplot(
res_df=res_df,
x_col='param_' + grid_name,
y_col='mean_test_score',
xlog10=False if grid_name != 'n_epochs' else True,
xlog10plusone=False,
custom_x_ticks=None if grid_name != 'n_epochs' else 'log10_scale',
x_label=grid_name,
y_label='Macro F1',
x_axis_grid=True,
dpi=300,
)
plt.tight_layout()
plt.savefig(os.path.join(current_save_p, f'{grid_name}.png'))
plt.close('all')
def main_som_parameter_tuning():
"""
Script for running hyperparameter tuning on the immune status dataset. The workflow is as follows:
- Preprocessed data is loaded.
- Data is downsampled to 10% of all events for faster training.
- Data is split into train and val.
- Results are printed and saved.
The following flags are defined in the header and can be adjusted as needed:
- inference (bool), whether to do the training or just load and print previously generated results.
- random_seed (int)
- downsampling_frac (float)
- val_frac (float), relative size of the validation set
- n_epochs (int)
Returns:
None
"""
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, PredefinedSplit
from flagx.gating import SomClassifier
from validation.utils import set_pandas_print_options, get_downsampling_bool
# ### Set flags and variables ######################################################################################
inference = True # Whether to do the hyperparameter tuning or just view the results
trafo = 'log10_w_custom_cutoffs'
random_seed = 42
downsampling_frac = 0.10
val_frac = 0.34
grid = 'full_grid' # 'full_grid', 'test'
n_epochs = 6000
####################################################################################################################
# Define dir for saving the results
save_p = os.path.join(os.getcwd(), f'results/som_parameter_tuning/{trafo}/{grid}')
os.makedirs(save_p, exist_ok=True)
# ### Load the train data
data_p_default = os.path.join(f'./data/np_files/imstat/{trafo}')
data_p_hpc = f'/home/woody/iwbn/iwbn107h/data/np_files/imstat/{trafo}'
if os.path.exists(data_p_hpc):
data_p = data_p_hpc
elif os.path.exists(data_p_default):
data_p = data_p_default
else:
raise RuntimeError(f'\n# ### No data found at:\nhpc: "{data_p_hpc}"\ndefault: "{data_p_default}".')
x = np.load(os.path.join(data_p, 'x_train.npy')).astype(np.float32)
y = np.load(os.path.join(data_p, 'y_train.npy')).astype(np.int32)
# ### Downsample for faster training
np.random.seed(random_seed)
target_num_events = int(x.shape[0] * downsampling_frac)
print((
f'# ### Downsampling training data from {x.shape[0]} events '
f'to {target_num_events} events ({int(downsampling_frac * 100)} %)'
))
downsampling_bool = get_downsampling_bool(y=y, target_num_events=target_num_events, stratified=True)
x = x[downsampling_bool, :]
y = y[downsampling_bool]
# ### Split data into train and val set (performance was observed to be stable across folds => No more cv here)
x_train, x_val, y_train, y_val = train_test_split(
x, y,
test_size=val_frac,
stratify=y,
random_state=random_seed,
)
# Reconcatenate the data (first train, then val)
x = np.vstack((x_train, x_val))
y = np.hstack((y_train, y_val))
# Create a PredefinedSplit according to the previous data split
# (https://scikit-learn.org/1.5/modules/cross_validation.html#predefined-split)
val_fold = [-1] * x_train.shape[0] + [0] * x_val.shape[0]
cv = PredefinedSplit(test_fold=val_fold)
# ### Define parameter grid, based on the previous experiments
if grid == 'full_grid':
param_grid = {
'som_topology': ['planar', ],
'som_grid_type': ['rectangular', ],
'som_dimensions': [(15, 15), (20, 20), (25, 25)],
'neighborhood': ['gaussian', ],
'gaussian_neighborhood_sigma': [0.1, 0.5, 1.0],
'initialization': ['pca', ],
'n_epochs': [n_epochs, ],
'radius_0': [-0.25, -0.5, -0.75],
'radius_n': [0.1, ],
'radius_cooling': ['exponential', ],
'learning_rate_0': [0.1, 0.5, 1.0],
'learning_rate_n': [0.001, 0.05, 0.1],
'learning_rate_decay': ['exponential', ],
}
else: # test
param_grid = {
'som_topology': ['planar', ],
'som_grid_type': ['rectangular', ],
'som_dimensions': [(15, 15), (20, 20), (25, 25)],
'neighborhood': ['gaussian', ],
'gaussian_neighborhood_sigma': [0.5, ],
'initialization': ['pca', ],
'n_epochs': [50, ],
'radius_0': [-0.75, ],
'radius_n': [0.75, ],
'radius_cooling': ['linear', ],
'learning_rate_0': [0.1, ],
'learning_rate_n': [0.01, ],
'learning_rate_decay': ['exponential', ],
}
# ### Inference
if inference:
# Instantiate the SOM classifier
som_clf = SomClassifier(verbosity=2)
# Perform the hyperparameter tuning
som_clf.hyperparameter_tuning(
X=x,
y=y,
param_grid=param_grid,
cv=cv,
scoring='internal',
refit=False
)
# Save the SOM classifier
som_clf.save(filepath=save_p)
else:
som_clf = SomClassifier.load(filepath=save_p)
res_df = pd.DataFrame(som_clf.grid_search_.cv_results_)
res_df.to_csv(os.path.join(save_p, f'res_df.csv'))
set_pandas_print_options()
print('# ### Results:\n', res_df)
print('# ### Best parameters:\n', som_clf.grid_search_.best_params_)
print('# ### Best score:\n', som_clf.grid_search_.best_score_)
def main_som_n_epochs_calibration():
"""
Script for finding the optimal number of epochs to train for given a set of optimized parameters.
The workflow is as follows:
- Preprocessed data is loaded.
- Data is split into train and val. (No downsampling!)
- Results are printed and saved.
The following flags are defined in the header and can be adjusted as needed:
- inference (bool), whether to do the training or just load and print previously generated results.
- random_seed (int)
- val_frac (float), relative size of the validation set
- n_epochs (int)
Returns:
None
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, PredefinedSplit
from flagx.gating import SomClassifier
from validation.utils import set_pandas_print_options
from validation.plt import plot_param_lineplot
# ### Set flags and variables ######################################################################################
inference = True # Whether to do the hyperparameter tuning or just view the results
trafo = 'log10_w_custom_cutoffs'
random_seed = 42
val_frac = 0.34
# Gridsearch for n_epochs
n_epochs = list(range(10, 101, 10)) + list(range(200, 2001, 100)) + list(range(2500, 6001, 500))
####################################################################################################################
# ### Load the train data
data_p = f'./data/np_files/imstat/{trafo}'
x = np.load(os.path.join(data_p, 'x_train.npy')).astype(np.float32)
y = np.load(os.path.join(data_p, 'y_train.npy')).astype(np.int32)
# ### Split data into train and val set (performance was observed to be stable across folds => No more cv here)
x_train, x_val, y_train, y_val = train_test_split(
x, y,
test_size=val_frac,
stratify=y,
random_state=random_seed,
)
# Reconcatenate the data (first train, then val)
x = np.vstack((x_train, x_val))
y = np.hstack((y_train, y_val))
# Create a PredefinedSplit according to the previous data split
# (https://scikit-learn.org/1.5/modules/cross_validation.html#predefined-split)
val_fold = [-1] * x_train.shape[0] + [0] * x_val.shape[0]
cv = PredefinedSplit(test_fold=val_fold)
# Load the previously optimized parameters and define a parameter grid with them
som_clf_param_tuning = SomClassifier.load(filepath=f'./results/som_parameter_tuning/{trafo}/full_grid')
best_params = som_clf_param_tuning.grid_search_.best_params_
print('# --- Best parameters:')
for key, value in best_params.items():
print(f'# {key}: {value}')
# Define dir for saving the results
save_p = f'./results/som_n_epochs_calibration/{trafo}'
os.makedirs(save_p, exist_ok=True)
# ### Inference
if inference:
# Instantiate the SOM classifier with the best parameters
som_clf = SomClassifier(verbosity=1, **best_params)
# Perform the hyperparameter tuning
som_clf.hyperparameter_tuning(
X=x,
y=y,
param_grid={'n_epochs': n_epochs},
cv=cv,
scoring='internal',
refit=False
)
# Save the SOM classifier
som_clf.save(filepath=save_p)
else:
som_clf = SomClassifier.load(filepath=save_p)
res_df = pd.DataFrame(som_clf.grid_search_.cv_results_)
res_df.to_csv(os.path.join(save_p, f'res_df.csv'))
set_pandas_print_options()
print('# ### Results:\n', res_df)
print('# ### Best parameters:\n', som_clf.grid_search_.best_params_)
print('# ### Best score:\n', som_clf.grid_search_.best_score_)
plot_param_lineplot(
res_df=res_df,
x_col='param_n_epochs',
y_col='mean_test_score',
xlog10=True,
xlog10plusone=False,
custom_x_ticks='log10_scale',
x_label='n epochs',
y_label='Macro F1',
dpi=300,
)
plt.tight_layout()
plt.savefig(os.path.join(save_p, 'n_epochs.png'))
plt.close('all')
def main_som_classifier():
"""
Runs training, prediction, and evaluation for the SOM classifier across multiple datasets.
This script loads preprocessed data, trains the SOM classifier with previously optimized parameters,
performs sample-wise and concatenated predictions, computes evaluation metrics,
tracks runtime performance, and stores all outputs in the results directory.
The function supports HPC and local file paths and handles automatic loading of
existing models and predictions when fitting or prediction is disabled.
Saves:
- Trained SOM classifier
- Runtime statistics.
- Predictions (full test set and sample-wise).
- Evaluation metrics (average, class-wise, sample-wise).
- Confusion matrices and abstention counts.
"""
import os
import numpy as np
import pandas as pd
from flagx.gating import SomClassifier
from validation.utils import eval_wrapper, eval_wrapper_sample_wise, scalability_wrapper
# ### Set flags and important variables here #######################################################################
data_sets = [
'imstat', 'lymphoma_tube1', 'lymphoma_tube2', 'lymphoma_tube1_binary', 'lymphoma_tube2_binary', 'flowcyt'
]
others_labels = [8, None, None, None, None, 5]
pos_labels = [None, None, None, 1, 1, None]
preprocessing_trafo = 'log10_w_custom_cutoffs'
fit = True
predict = True
evaluate = True
####################################################################################################################
for data_set, others_label, pos_label in zip(data_sets, others_labels, pos_labels):
if preprocessing_trafo == 'log10_w_custom_cutoffs' and data_set == 'flowcyt':
trafo = 'log10_cutoff100'
else:
trafo = preprocessing_trafo
print(f'# ###### Data set: {data_set}, trafo: {trafo} ###### #')
# Check whether train data exists for this dataset and trafo, if not continue
data_p_default = os.path.join(f'./data/np_files/{data_set}/{trafo}')
data_p_hpc = f'/home/woody/iwbn/iwbn107h/data/np_files/{data_set}/{trafo}'
if os.path.exists(data_p_hpc):
data_p = data_p_hpc
elif os.path.exists(data_p_default):
data_p = data_p_default
else:
print(f'\n# ### No data found at:\nhpc: "{data_p_hpc}"\ndefault: "{data_p_default}".\nContinue.')
continue
# Define path where results will be saved to
save_p = os.path.join(os.getcwd(), f'./results/gating_performance/som/{data_set}/{trafo}')
os.makedirs(save_p, exist_ok=True)
if fit:
# Load training data
x_train = np.load(os.path.join(data_p, 'x_train.npy'))
y_train = np.load(os.path.join(data_p, 'y_train.npy'))
# Instantiate the SOM classifier
som_clf = SomClassifier(
som_topology='planar',
som_grid_type='rectangular',
som_dimensions=(25, 25),
neighborhood='gaussian',
gaussian_neighborhood_sigma=0.1,
initialization='pca',
n_epochs=1000,
radius_0=-0.5,
radius_n=0.1,
radius_cooling='exponential',
learning_rate_0=0.1,
learning_rate_n=0.001,
learning_rate_decay='exponential',
verbosity=2,
)
# Fit and track time
print('# ### Starting fit ...')
def dummy_fit():
som_clf.fit(X=x_train, y=y_train)
return som_clf
fit_time_df, som_clf = scalability_wrapper(function=dummy_fit, function_params=None, track_gpu=False)
fit_time_df.to_csv(os.path.join(save_p, 'fit_time_df.csv'))
som_clf.save(filepath=save_p)
else:
# Load the SOM classifier
som_clf = SomClassifier.load(filepath=save_p)
if predict:
# Load the test data
x_test = np.load(os.path.join(data_p, 'x_test.npy'))
print('# ### Starting prediction ...')
def dummy_predict():
return som_clf.predict(X=x_test)
pred_time_df, y_pred = scalability_wrapper(function=dummy_predict, function_params=None, track_gpu=False)
pred_time_df.to_csv(os.path.join(save_p, 'pred_time_df.csv'))
np.save(os.path.join(save_p, 'y_pred.npy'), y_pred)
# Load the sample-wise test data
samples_p = os.path.join(data_p, 'sample_wise_test')
n_samples = len([f for f in os.listdir(samples_p) if f.startswith('x_')])
sample_names = [f'sample_{str(i).zfill(2)}_test' for i in range(n_samples)]
samples_x_test_filenames = [f'x_{sn}.npy' for sn in sample_names]
samples_x_test = [np.load(os.path.join(samples_p, f)) for f in samples_x_test_filenames]
samples_y_pred = []
samples_pred_time_dfs = []
print('# ### Starting sample-wise prediction ...')
for x, sn in zip(samples_x_test, sample_names):
def dummy_predict_sample():
return som_clf.predict(X=x)
pred_time_df_sample, y_pred_sample = scalability_wrapper(
function=dummy_predict_sample, function_params=None, track_gpu=False
)
pred_time_df_sample['sample_name'] = sn
samples_y_pred.append(y_pred_sample)
samples_pred_time_dfs.append(pred_time_df_sample)
samples_pred_times_df = pd.concat(samples_pred_time_dfs, ignore_index=True)
samples_pred_times_df.to_csv(os.path.join(save_p, 'samples_pred_times_df.csv'))
os.makedirs(os.path.join(save_p, 'samples_y_pred'), exist_ok=True)
for y, sn in zip(samples_y_pred, sample_names):
np.save(os.path.join(save_p, 'samples_y_pred', f'y_pred_{sn}.npy'), y)
else:
# Load the predictions
y_pred = np.load(os.path.join(save_p, 'y_pred.npy'))