-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_classification.py
1505 lines (1385 loc) · 58.6 KB
/
binary_classification.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
"""Binary Classification module.
This module can be ran as a script to perform binary classification on the DHG
dataset or imported as a module to use the functions. Contains the following:
* main - Function to run binary classification on the DHG dataset.
"""
import os
import argparse
import json
import random
import warnings
import optuna
import shap
import numpy as np
import pandas as pd
import seaborn as sns
import figure_customizer as fc
from pathlib import Path
from tqdm import tqdm
from matplotlib import pyplot as plt
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.model_selection import StratifiedGroupKFold
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from joblib import Parallel, delayed
from typing import List, Tuple, Dict, Any, Union
def load_data(
processed_files: List[Path], metadata_df: pd.DataFrame
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray]:
"""Function to load the data.
Args:
processed_files (List[Path]): List of processed files.
metadata_df (pd.DataFrame): Metadata dataframe.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray]: A tuple containing the spectras, file names, sample
file names, sample numbers, sample types, and WHO grades.
"""
# Define lists to store the data
spectras = []
file_names = []
sample_file_names = []
sample_numbers = []
sample_types = []
who_grades = []
# Loop through the processed files
for p in processed_files:
# Get the spectras
img = np.load(p / "mapped_tic_normalized.npy")
seg = np.load(p / "segmentation.npy")
spectras.append(img[seg])
num_spectras = img[seg].shape[0]
# Get the file name, sample file name, sample number, sample type, and
# WHO grade
metadata = metadata_df[metadata_df.sample_file_name == p.stem]
file_name = metadata.file_name.values[0]
sample_file_name = metadata.sample_file_name.values[0]
sample_number = metadata.sample_number.values[0]
sample_type = metadata.sample_type.values[0]
who_grade = metadata.who_grade.values[0]
# Append to the lists
file_names.append([file_name] * num_spectras)
sample_file_names.append([sample_file_name] * num_spectras)
sample_numbers.append([sample_number] * num_spectras)
sample_types.append([sample_type] * num_spectras)
who_grades.append([who_grade] * num_spectras)
# Convert lists to numpy arrays
return (
np.concatenate(spectras), np.concatenate(file_names),
np.concatenate(sample_file_names), np.concatenate(sample_numbers),
np.concatenate(sample_types), np.concatenate(who_grades)
)
def separate_data_by_sample_type(
X: np.ndarray, y: np.ndarray, batch_ids: np.ndarray,
patient_ids: np.ndarray, sample_types: np.ndarray
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray, np.ndarray, np.ndarray]:
"""Function to separate the data by sample type.
Args:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
batch_ids (np.ndarray): The batch IDs.
patient_ids (np.ndarray): The patient IDs.
sample_types (np.ndarray): The sample types.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray, np.ndarray, np.ndarray]: A tuple containing the replica
feature matrix, section feature matrix, replica target vector,
section target vector, replica batch IDs, section batch IDs,
replica patient IDs, and section patient IDs.
"""
return (
X[sample_types == 'replica'], X[sample_types == 'section'],
y[sample_types == 'replica'], y[sample_types == 'section'
], batch_ids[sample_types == 'replica'],
batch_ids[sample_types == 'section'
], patient_ids[sample_types == 'replica'
], patient_ids[sample_types == 'section']
)
def prepare_grouped_indices(batch_ids: np.ndarray) -> Dict[Any, np.ndarray]:
"""Function to prepare grouped indices for LOOCV.
Args:
batch_ids (np.ndarray): Array of batch IDs.
Returns:
Dict[Any, np.ndarray]: A dictionary containing the unique batch IDs as keys
and the corresponding indices as values.
"""
# Get unique values of batch IDs
unique_vals = np.unique(batch_ids)
# Create a dictionary to store the grouped indices
grouped_indices = {val: np.where(batch_ids == val)[0] for val in unique_vals}
return grouped_indices
def objective(
trial, model_type: str, X_train: np.ndarray, y_train: np.ndarray,
batch_ids_train: np.ndarray, seed: int
) -> float:
"""
Objective function for Optuna to optimize hyperparameters of a model using
cross-validation.
Args:
trial (optuna.trial.Trial): A trial object that suggests hyperparameters.
X_train (np.ndarray): Training feature matrix of shape (n_samples,
n_features).
y_train (np.ndarray): Training target vector of shape (n_samples,).
batch_ids (np.ndarray): Array of group IDs used to group samples for
cross-validation.
seed (int): Random seed for reproducibility.
Returns:
float: The mean AUC score across the cross-validation folds for the
suggested hyperparameters.
"""
# Suggest hyperparameters using Optuna for Logistic Regression
if model_type == 'logistic_regression':
C = trial.suggest_float('C', 1e-6, 1e+6, log=True)
max_iter = trial.suggest_int('max_iter', 100, 1000)
tol = trial.suggest_float('tol', 1e-4, 1e-2, log=True)
solver = trial.suggest_categorical('solver', ['liblinear', 'lbfgs'])
model = LogisticRegression(
C=C, max_iter=max_iter, tol=tol, solver=solver, random_state=seed
)
# Suggest hyperparameters using Optuna for Random Forest
elif model_type == 'random_forest':
n_estimators = trial.suggest_int('n_estimators', 50, 200)
max_depth = trial.suggest_int('max_depth', 3, 7)
max_features = trial.suggest_categorical(
'max_features', ['sqrt', 'log2', None]
)
model = RandomForestClassifier(
n_estimators=n_estimators, max_depth=max_depth,
max_features=max_features, random_state=seed
)
# Suggest hyperparameters using Optuna for XGBoost
elif model_type == 'xgboost':
max_depth = trial.suggest_int('max_depth', 3, 7)
learning_rate = trial.suggest_float('learning_rate', 0.01, 0.1, log=True)
subsample = trial.suggest_float('subsample', 0.6, 1.0)
colsample_bytree = trial.suggest_float('colsample_bytree', 0.6, 1.0)
gamma = trial.suggest_float('gamma', 0, 5)
n_estimators = trial.suggest_int('n_estimators', 50, 200)
model = XGBClassifier(
max_depth=max_depth, learning_rate=learning_rate, subsample=subsample,
colsample_bytree=colsample_bytree, gamma=gamma,
n_estimators=n_estimators, random_state=seed
)
# Suggest hyperparameters using Optuna for LightGBM
else:
max_depth = trial.suggest_int('max_depth', 3, 7)
learning_rate = trial.suggest_float('learning_rate', 0.01, 0.1, log=True)
num_leaves = trial.suggest_int('num_leaves', 15, 50)
n_estimators = trial.suggest_int('n_estimators', 50, 200)
feature_fraction = trial.suggest_float('feature_fraction', 0.6, 1.0)
model = LGBMClassifier(
num_leaves=num_leaves, learning_rate=learning_rate,
feature_fraction=feature_fraction, n_estimators=n_estimators,
max_depth=max_depth, random_state=seed, verbose=-1
)
# Define cross-validation
skf = StratifiedGroupKFold(n_splits=3, shuffle=False)
# Define predictions array
predictions = np.zeros(y_train.shape)
# Perform cross-validation with the suggested hyperparameters
for train_idx, val_idx in skf.split(X_train, y_train, batch_ids_train):
X_tr, X_val = X_train[train_idx], X_train[val_idx]
y_tr, _ = y_train[train_idx], y_train[val_idx]
with warnings.catch_warnings():
# Suppress specific warnings during hyperparameter tuning
warnings.simplefilter("ignore", category=ConvergenceWarning)
model.fit(X_tr, y_tr)
predictions[val_idx] = model.predict_proba(X_val)[:, 1]
# Calculate AUC score and return
return roc_auc_score(y_train, predictions)
def optimize_hyperparameters(
X_train: np.ndarray, y_train: np.ndarray, batch_ids_train: np.ndarray,
model_type: str, seed: int, n_trials: int = 50, n_jobs: int = -1
) -> Dict[str, Any]:
"""Function to optimize hyperparameters using Optuna.
Args:
X_train (np.ndarray): Training feature matrix.
y_train (np.ndarray): Training target vector.
batch_ids_train (np.ndarray): Array of group IDs used to group samples for
cross-validation.
model_type (str): The type of model to optimize hyperparameters for.
seed (int): Random seed for reproducibility.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
Dict[str, Any]: A dictionary containing the best hyperparameters found
"""
study = optuna.create_study(direction='maximize')
study.optimize(
lambda trial:
objective(trial, model_type, X_train, y_train, batch_ids_train, seed),
n_trials=n_trials, n_jobs=n_jobs
)
return study.best_params
def create_best_model(
model_type: str, best_params: Dict[str, Any], seed: int
) -> Union[LogisticRegression, XGBClassifier, RandomForestClassifier,
LGBMClassifier]:
"""Function to create the best model using the best hyperparameters.
Args:
model_type (str): he type of model to optimize hyperparameters for.
best_params (Dict[str, Any]): Dictionary of best hyperparameters found.
seed (int): Random seed for reproducibility.
Returns:
Union[LogisticRegression, DecisionTreeClassifier, XGBClassifier,
RandomForestClassifier, LGBMClassifier]: The best model.
"""
# Create the best model for Logistic Regression
if model_type == 'logistic_regression':
best_model = LogisticRegression(**best_params, random_state=seed)
# Create the best model for XGBoost
elif model_type == 'xgboost':
best_model = XGBClassifier(**best_params, random_state=seed)
# Create the best model for Random Forest
elif model_type == 'random_forest':
best_model = RandomForestClassifier(**best_params, random_state=seed)
# Create the best model for LightGBM
else:
best_model = LGBMClassifier(**best_params, random_state=seed, verbose=-1)
return best_model
def fit_and_predict_model(
X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray,
model_type: str, best_params: Dict[str, Any], seed: int
) -> np.ndarray:
"""Function to fit and predict a model using the best hyperparameters.
Args:
X_train (np.ndarray): Training feature matrix.
y_train (np.ndarray): Training target vector.
X_test (np.ndarray): Test feature matrix.
model_type (str): The type of model to optimize hyperparameters for.
best_params (Dict[str, Any]): Dictionary of best hyperparameters found.
seed (in): Random seed for reproducibility.
Returns:
np.ndarray: Predictions for the test set.
"""
# Create and fit the model using the best parameters
best_model = create_best_model(model_type, best_params, seed)
best_model.fit(X_train, y_train)
# Make predictions
return best_model.predict_proba(X_test)[:, 1]
def train_and_predict_for_group(
X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray,
X_test_other: np.ndarray, batch_ids_train: np.ndarray, model_type: str,
seed: int, best_params: Dict[str, Any] = None, n_trials: int = 50,
n_jobs: int = -1
) -> Tuple[np.ndarray, np.ndarray, Dict[str, Any]]:
"""Function to train and predict for a group of samples.
Args:
X_train (np.ndarray): Training feature matrix.
y_train (np.ndarray): Training target vector.
X_test (np.ndarray): Test feature matrix.
X_test_other (np.ndarray): Test feature matrix for the other sample type.
batch_ids_train (np.ndarray): Array of group IDs used to group samples for
cross-validation.
model_type (str): The type of model to optimize hyperparameters for.
seed (int): Random seed for reproducibility.
best_params (Dict[str, Any], optional): Dictionary of best hyperparameters
found. Defaults to None.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
Tuple[np.ndarray, np.ndarray, Dict[str, Any]]: A tuple containing the
predictions for the replica samples, predictions for the section
samples, and the best hyperparameters found.
"""
# Get the best hyperparameters if not provided
if best_params is None:
best_params = optimize_hyperparameters(
X_train, y_train, batch_ids_train, model_type, seed, n_trials, n_jobs
)
# Combine X_test and X_test_other for prediction
X_test_combined = np.concatenate([X_test, X_test_other])
# Predict for combined data
preds_combined = fit_and_predict_model(
X_train, y_train, X_test_combined, model_type, best_params, seed
)
# Separate the predictions for replica and section and return them
return preds_combined[:len(X_test)], preds_combined[len(X_test):], best_params
def perform_loocv(
X: np.ndarray, y: np.ndarray, batch_ids: np.ndarray,
patient_ids: np.ndarray, other_X: np.ndarray, other_patient_ids: np.ndarray,
model_type: str, seed: int, best_params_list: List[Dict[str, Any]] = None,
n_trials: int = 50, n_jobs: int = -1
) -> Tuple[np.ndarray, np.ndarray, List[Dict[str, Any]]]:
""" Function to perform leave-one-out cross-validation.
Args:
X (np.ndarray): Training feature matrix.
y (np.ndarray): Training target vector.
batch_ids (np.ndarray): Array of group IDs used to group samples for
patient_ids (np.ndarray): Array of patient IDs.
other_X (np.ndarray): Test feature matrix for the other sample type.
other_patient_ids (np.ndarray): Array of patient IDs for the other sample
model_type (str): The type of model to optimize hyperparameters for.
seed (int): Random seed for reproducibility.
best_params_list (List[Dict[str, Any]], optional): List of best
hyperparameters found. Defaults to None.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
Tuple[np.ndarray, np.ndarray, List[Dict[str, Any]]]: A tuple containing the
predicted probabilities for the replica samples, predicted probabilities
for the section samples, and the best hyperparameters used.
"""
# Prepare grouped indices for LOOCV
grouped_indices = prepare_grouped_indices(batch_ids)
# Arrays to store predicted probabilities and best parameters used
predicted_probabilities = np.zeros(X.shape[0])
predicted_probabilities_cross = np.zeros(other_X.shape[0])
best_params_used = []
# Loop over each group for training and testing
for idx, (_, test_idx) in tqdm(
enumerate(grouped_indices.items()), total=len(grouped_indices),
desc="LOOCV"
):
# Define train indices by excluding patients in the test set
train_idx = ~np.isin(patient_ids, patient_ids[test_idx])
# Identify cross-test indices in the other sample type that correspond to
# the same patients
cross_test_idx = np.isin(other_patient_ids, patient_ids[test_idx])
# Get the best parameters if provided, otherwise train and optimize
best_params = best_params_list[idx] if best_params_list else None
# Perform training and prediction
preds, preds_cross, best_params = train_and_predict_for_group(
X[train_idx], y[train_idx], X[test_idx], other_X[cross_test_idx],
batch_ids[train_idx], model_type, seed, best_params, n_trials, n_jobs
)
# Store the predictions
predicted_probabilities[test_idx] = preds
predicted_probabilities_cross[cross_test_idx] = preds_cross
best_params_used.append(best_params)
# Return the predicted probabilities and the best parameters used
return (
predicted_probabilities, predicted_probabilities_cross, best_params_used
)
def single_seed_loocv(
X: np.ndarray, y: np.ndarray, batch_ids: np.ndarray,
patient_ids: np.ndarray, sample_types: np.ndarray, model_type: str,
seed: int, best_params_r: Dict[str, Any] = None,
best_params_s: Dict[str, Any] = None, n_trials: int = 50, n_jobs: int = -1
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any], Dict[
str, Any]]:
"""Function to perform loocv classification using a single seed.
Args:
X (np.ndarray): Training feature matrix.
y (np.ndarray): Training target vector.
batch_ids (np.ndarray): Array of group IDs used to group samples for
patient_ids (np.ndarray): Array of patient IDs.
sample_types (np.ndarray): Array of sample types.
model_type (str): The type of model to optimize hyperparameters for.
seed (int): Random seed for reproducibility.
best_params_r (Dict[str, Any]): Best hyperparameters for replica samples.
Defaults to None.
best_params_s (Dict[str, Any]): Best hyperparameters for section samples.
Defaults to None.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, Dict[str, Any],
Dict[str, Any]]: A tuple containing the predicted probabilities for
the replica samples, predicted probabilities for the section samples,
predicted probabilities for replica samples using section models,
predicted probabilities for section samples using replica models,
best hyperparameters for replica samples, and best hyperparameters for
section samples.
"""
# Separate the data based on the sample type
(X_r, X_s, y_r, y_s, batch_ids_r, batch_ids_s, patient_ids_r, patient_ids_s
) = separate_data_by_sample_type(X, y, batch_ids, patient_ids, sample_types)
# Perform LOOCV for replicas and sections
(predicted_probabilities_r, predicted_probabilities_rs,
best_params_r) = perform_loocv(
X_r, y_r, batch_ids_r, patient_ids_r, X_s, patient_ids_s, model_type,
seed, best_params_r, n_trials, n_jobs
)
(predicted_probabilities_s, predicted_probabilities_sr,
best_params_s) = perform_loocv(
X_s, y_s, batch_ids_s, patient_ids_s, X_r, patient_ids_r, model_type,
seed, best_params_s, n_trials, n_jobs
)
# Return the predicted probabilities
return (
predicted_probabilities_r, predicted_probabilities_s,
predicted_probabilities_rs, predicted_probabilities_sr, best_params_r,
best_params_s
)
def single_seed_classification(
seed: int, spectras: np.ndarray, file_names: np.ndarray,
sample_numbers: np.ndarray, sample_types: np.ndarray,
who_grades: np.ndarray, model_type: str,
best_params_r: Dict[str, Any] = None, best_params_s: Dict[str, Any] = None,
n_trials: int = 50, n_jobs: int = -1, output_dir: str = "output"
) -> None:
"""Function to run classification with a single seed.
Args:
seed (int): Seed for reproducibility.
spectras (np.ndarray): Spectras.
file_names (np.ndarray): File names.
sample_numbers (np.ndarray): Sample numbers.
sample_types (np.ndarray): Sample types.
who_grades (np.ndarray): WHO grades.
model_type (str): The type of model to optimize hyperparameters for.
best_params_r (Dict[str, Any], optional): Best hyperparameters for replica
samples. Defaults to None.
best_params_s (Dict[str, Any], optional): Best hyperparameters for section
samples. Defaults to None.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
output_dir (str, optional): Output directory to save the results.
"""
# Set the seed for reproducibility
np.random.seed(seed)
random.seed(seed)
# Create a folder for the seed
seed_dir = output_dir / f"seed_{seed}"
seed_dir.mkdir(parents=True, exist_ok=True)
# Run classification
(
predicted_probabilities_r, predicted_probabilities_s,
predicted_probabilities_rs, predicted_probabilities_sr, best_params_r,
best_params_s
) = single_seed_loocv(
spectras.copy(), (who_grades > 2).astype(int), file_names.copy(),
sample_numbers.copy(), sample_types.copy(), model_type, seed,
best_params_r, best_params_s, n_trials, n_jobs
)
# Save results
np.save(seed_dir / "predicted_probabilities_r.npy", predicted_probabilities_r)
np.save(seed_dir / "predicted_probabilities_s.npy", predicted_probabilities_s)
np.save(
seed_dir / "predicted_probabilities_rs.npy", predicted_probabilities_rs
)
np.save(
seed_dir / "predicted_probabilities_sr.npy", predicted_probabilities_sr
)
with open(seed_dir / "best_params_r.json", 'w') as f:
json.dump(best_params_r, f)
with open(seed_dir / "best_params_s.json", 'w') as f:
json.dump(best_params_s, f)
def multiple_seeds_classification_with_parallel(
primary_seed: int, iterations: int, model_type: str,
processed_files: List[Path], metadata_df: pd.DataFrame, output_dir: Path,
n_trials: int = 50, n_jobs: int = -1
) -> List[int]:
"""Function to run classification with multiple seeds in parallel.
Args:
primary_seed (int): Seed for reproducibility.
iterations (int): Number of iterations to run.
model_type (str): Type of model to use for classification.
processed_files (List[Path]): List of processed files.
metadata_df (pd.DataFrame): Metadata dataframe.
output_dir (Path): Output directory to save the results.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
List[int]: List of seeds used for each classification.
"""
# Set the primary seed for reproducibility
np.random.seed(primary_seed)
random.seed(primary_seed)
# Load the data
(
spectras, file_names, sample_file_names, sample_numbers, sample_types,
who_grades
) = load_data(processed_files, metadata_df)
# Generate multiple seeds for evaluation
evaluation_seeds = [primary_seed] + [
int(i) for i in
np.random.choice(range(10000), size=iterations - 1, replace=False)
]
# Create the output directory if it does not exist
output_dir_path = Path(output_dir)
output_dir_path.mkdir(parents=True, exist_ok=True)
# Use joblib to run the function in parallel for each seed
results = [
r for r in tqdm(
Parallel(return_as="generator", n_jobs=n_jobs)(
delayed(single_seed_classification)(
seed=seed, spectras=spectras, file_names=file_names,
sample_numbers=sample_numbers, sample_types=sample_types,
who_grades=who_grades, model_type=model_type,
n_trials=n_trials, n_jobs=n_jobs, output_dir=output_dir_path
) for seed in evaluation_seeds
), total=len(evaluation_seeds),
desc="Running classification for multiple seeds"
)
]
# Return the list of seeds used for reference
return evaluation_seeds
def get_best_params_from_best_seed(
model_output_dir: Path, who_grades_r: np.ndarray, who_grades_s: np.ndarray
) -> Tuple[Dict[str, Any], Dict[str, Any], int, int]:
""" Function to get the best parameters from the best seed.
Args:
model_output_dir (Path): Path to the output directory containing model
saved results.
who_grades_r (np.ndarray): WHO grades for non-bulk data (replica).
who_grades_s (np.ndarray): WHO grades for non-bulk data (section).
Returns:
Tuple[Dict[str, Any], Dict[str, Any], int, int]: Best parameters for
replica and section data and the seeds used for classification.
"""
# Initialize lists to store true labels and predictions
y_true_r = (who_grades_r > 2).astype(int)
y_true_s = (who_grades_s > 2).astype(int)
# Define variables to store the best AUC scores
best_auc_r, best_auc_s, best_auc_rs, best_auc_sr = (
-np.inf, -np.inf, -np.inf, -np.inf
)
# Initialize best parameters
best_params_r, best_params_s = None, None
#
seed_r, seed_s = None, None
# Loop through each seed and load the saved predictions
for seed_dir in model_output_dir.glob("seed_*"):
if len(list(seed_dir.glob("*.npy"))) == 0:
continue
# Load predicted probabilities
pred_r = np.load(seed_dir / "predicted_probabilities_r.npy")
pred_s = np.load(seed_dir / "predicted_probabilities_s.npy")
# Calculate ROC curves for each category
auc_r = roc_auc_score(y_true_r, pred_r)
auc_s = roc_auc_score(y_true_s, pred_s)
# Check if the current model is better than the previous best model
if auc_r > best_auc_r:
best_auc_r = auc_r
best_params_r = json.load(open(seed_dir / "best_params_r.json"))
seed_r = int(seed_dir.stem.split("_")[-1])
# Check if the current model is better than the previous best model
if auc_s > best_auc_s:
best_auc_s = auc_s
best_params_s = json.load(open(seed_dir / "best_params_s.json"))
seed_s = int(seed_dir.stem.split("_")[-1])
return best_params_r, best_params_s, seed_r, seed_s
def get_params_from_median_seed(
model_output_dir: Path, who_grades_r: np.ndarray, who_grades_s: np.ndarray
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
""" Function to get the parameters from the median seed.
Args:
model_output_dir (Path): Path to the output directory containing model
saved results.
who_grades_r (np.ndarray): WHO grades for non-bulk data (replica).
who_grades_s (np.ndarray): WHO grades for non-bulk data (section).
Returns:
Tuple[Dict[str, Any], Dict[str, Any], int, int]: Median parameters for
replica and section data and the seeds used for classification.
"""
# Initialize lists to store AUC scores for each seed
auc_scores_r = []
auc_scores_s = []
seed_dirs = []
# Initialize lists to store true labels and predictions
y_true_r = (who_grades_r > 2).astype(int)
y_true_s = (who_grades_s > 2).astype(int)
# Loop through each seed and load the saved predictions
for seed_dir in model_output_dir.glob("seed_*"):
if len(list(seed_dir.glob("*.npy"))) == 0:
continue
# Load predicted probabilities
pred_r = np.load(seed_dir / "predicted_probabilities_r.npy")
pred_s = np.load(seed_dir / "predicted_probabilities_s.npy")
# Calculate ROC curves for each category
auc_r = roc_auc_score(y_true_r, pred_r)
auc_s = roc_auc_score(y_true_s, pred_s)
# Append scores and seed_dir
auc_scores_r.append((auc_r, seed_dir))
auc_scores_s.append((auc_s, seed_dir))
seed_dirs.append(seed_dir)
# Sort the scores
auc_scores_r.sort(key=lambda x: x[0])
auc_scores_s.sort(key=lambda x: x[0])
# Find median AUC seed directories
median_index_r = len(auc_scores_r) // 2
median_index_s = len(auc_scores_s) // 2
median_seed_dir_r = auc_scores_r[median_index_r][1] if auc_scores_r else None
median_seed_dir_s = auc_scores_s[median_index_s][1] if auc_scores_s else None
# Get the seeds
median_seed_r = int(
median_seed_dir_r.stem.split("_")[-1]
) if median_seed_dir_r else None
median_seed_s = int(
median_seed_dir_s.stem.split("_")[-1]
) if median_seed_dir_s else None
# Get the best parameters from the median seed
best_params_r = json.load(open(median_seed_dir_r / "best_params_r.json"))
best_params_s = json.load(open(median_seed_dir_s / "best_params_s.json"))
return best_params_r, best_params_s, median_seed_r, median_seed_s
def single_seed_permutation(
seed: int, spectras: np.ndarray, file_names: np.ndarray,
sample_numbers: np.ndarray, sample_types: np.ndarray,
who_grades: np.ndarray, model_type: str, best_params_r: Dict[str, Any],
best_params_s: Dict[str, Any], output_dir: str = "output"
) -> int:
"""Function to run permutation classification with a single seed.
Args:
seed (int): Seed for reproducibility.
spectras (np.ndarray): Spectras.
file_names (np.ndarray): File names.
sample_numbers (np.ndarray): Sample numbers.
sample_types (np.ndarray): Sample types.
who_grades (np.ndarray): WHO grades.
model_type (str): The type of model to optimize hyperparameters for.
best_params_r (Dict[str, Any]): Best hyperparameters for replica
samples.
best_params_s (Dict[str, Any]): Best hyperparameters for section
samples.
output_dir (str, optional): Output directory to save the results.
Returns:
int : Seed used for classification.
"""
# Permute patient labels
rng = np.random.default_rng(seed)
unique_sample_numbers = np.unique(sample_numbers)
sample_numbers_who_grades = np.array(
[
who_grades[sample_numbers == s_num][0]
for s_num in unique_sample_numbers
]
)
permuted_sample_numbers_who_grades = rng.permutation(
sample_numbers_who_grades
)
who_grades_permuted = np.array(
[
permuted_sample_numbers_who_grades[np.where(
unique_sample_numbers == s_num
)[0][0]] for s_num in sample_numbers
]
)
# Run classification
single_seed_classification(
seed=seed, spectras=spectras, file_names=file_names,
sample_numbers=sample_numbers, sample_types=sample_types,
who_grades=who_grades_permuted, model_type=model_type,
best_params_r=best_params_r, best_params_s=best_params_s,
output_dir=output_dir
)
# Create a folder for the seed
seed_dir = output_dir / f"seed_{seed}"
seed_dir.mkdir(parents=True, exist_ok=True)
# Save the permuted sample numbers
np.save(
seed_dir / "permuted_sample_numbers_who_grades.npy",
permuted_sample_numbers_who_grades
)
# Return the seed used for classification
return seed
def permutation_classification_with_parallel(
primary_seed: int, permutations: int, model_type: str,
processed_files: List[Path], metadata_df: pd.DataFrame, model_dir: Path,
output_dir: Path, n_jobs: int = -1
) -> List[int]:
"""Function to run permutation classification with multiple seeds in parallel.
Args:
primary_seed (int): Seed for reproducibility.
permutations (int): Number of permutation to run.
model_type (str): Type of model to use for classification.
processed_files (List[Path]): List of processed files.
metadata_df (pd.DataFrame): Metadata dataframe.
model_dir (Path): Path to the directory containing the model saved results.
output_dir (Path): Output directory to save the results.
n_trials (int, optional): Number of trials for hyperparameter optimization.
n_jobs (int, optional): Number of parallel jobs to run.
Returns:
List[int]: List of seeds used for each classification.
"""
# Set the primary seed for reproducibility
np.random.seed(primary_seed)
random.seed(primary_seed)
# Load the data
(
spectras, file_names, sample_file_names, sample_numbers, sample_types,
who_grades
) = load_data(processed_files, metadata_df)
# Generate multiple seeds for permutation
permutation_seeds = [PRIMARY_SEED] + [
int(i) for i in
np.random.choice(range(10000), size=permutations - 1, replace=False)
]
# Create the output directory if it does not exist
output_dir.mkdir(parents=True, exist_ok=True)
# Get the best parameters from the best seed
"""
best_params_r, best_params_s, _, _ = get_best_params_from_best_seed(
model_dir, who_grades[sample_types == 'replica'],
who_grades[sample_types == 'section']
)
"""
best_params_r, best_params_s, _, _ = get_params_from_median_seed(
model_dir, who_grades[sample_types == 'replica'],
who_grades[sample_types == 'section']
)
# Use joblib to run the function in parallel for each seed
results = [
r for r in tqdm(
Parallel(return_as="generator", n_jobs=n_jobs)(
delayed(single_seed_permutation)(
seed=seed, spectras=spectras, file_names=file_names,
sample_numbers=sample_numbers, sample_types=sample_types,
who_grades=who_grades, best_params_r=best_params_r,
best_params_s=best_params_s, model_type=model_type,
output_dir=output_dir
) for seed in permutation_seeds
), total=len(permutation_seeds),
desc="Running Permutation for multiple seeds"
)
]
# Return the list of seeds used for reference
return permutation_seeds
def get_auc_from_best_seed(
model_output_dir: Path, who_grades_r: np.ndarray, who_grades_s: np.ndarray
) -> Tuple[float, ...]:
""" Function to get the auc from the best seed.
Args:
model_output_dir (Path): Path to the output directory containing model
saved results.
who_grades_r (np.ndarray): WHO grades for non-bulk data (replica).
who_grades_s (np.ndarray): WHO grades for non-bulk data (section).
Returns:
Tuple[float, ...]: Best auc for replica, section, replica-section, and
section-replica.
"""
# Initialize lists to store true labels and predictions
y_true_r = (who_grades_r > 2).astype(int)
y_true_s = (who_grades_s > 2).astype(int)
# Define variables to store the best AUC scores
best_auc_r, best_auc_s, best_auc_rs, best_auc_sr = (
-np.inf, -np.inf, -np.inf, -np.inf
)
# Loop through each seed and load the saved predictions
for seed_dir in model_output_dir.glob("seed_*"):
if len(list(seed_dir.glob("*.npy"))) == 0:
continue
# Load predicted probabilities
pred_r = np.load(seed_dir / "predicted_probabilities_r.npy")
pred_s = np.load(seed_dir / "predicted_probabilities_s.npy")
pred_rs = np.load(seed_dir / "predicted_probabilities_rs.npy")
pred_sr = np.load(seed_dir / "predicted_probabilities_sr.npy")
# Calculate ROC curves for each category
auc_r = roc_auc_score(y_true_r, pred_r)
auc_s = roc_auc_score(y_true_s, pred_s)
# Check if the current model is better than the previous best model
if auc_r > best_auc_r:
best_auc_r = auc_r
best_auc_rs = roc_auc_score(y_true_s, pred_rs)
# Check if the current model is better than the previous best model
if auc_s > best_auc_s:
best_auc_s = auc_s
best_auc_sr = roc_auc_score(y_true_r, pred_sr)
return best_auc_r, best_auc_s, best_auc_rs, best_auc_sr
def get_auc_from_median_seed(
model_output_dir: Path, who_grades_r: np.ndarray, who_grades_s: np.ndarray
) -> Tuple[float, ...]:
""" Function to get the auc from the median seed.
Args:
model_output_dir (Path): Path to the output directory containing model
saved results.
who_grades_r (np.ndarray): WHO grades for non-bulk data (replica).
who_grades_s (np.ndarray): WHO grades for non-bulk data (section).
Returns:
Tuple[float, ...]: Median auc for replica, section, replica-section, and
section-replica.
"""
# Initialize lists to store AUC scores for each seed
auc_scores_r = []
auc_scores_s = []
auc_scores_rs = []
auc_scores_sr = []
# Initialize lists to store true labels and predictions
y_true_r = (who_grades_r > 2).astype(int)
y_true_s = (who_grades_s > 2).astype(int)
# Loop through each seed and load the saved predictions
for seed_dir in model_output_dir.glob("seed_*"):
if len(list(seed_dir.glob("*.npy"))) == 0:
continue
# Load predicted probabilities
pred_r = np.load(seed_dir / "predicted_probabilities_r.npy")
pred_s = np.load(seed_dir / "predicted_probabilities_s.npy")
pred_rs = np.load(seed_dir / "predicted_probabilities_rs.npy")
pred_sr = np.load(seed_dir / "predicted_probabilities_sr.npy")
# Calculate AUC scores for each category
auc_r = roc_auc_score(y_true_r, pred_r)
auc_s = roc_auc_score(y_true_s, pred_s)
auc_rs = roc_auc_score(y_true_s, pred_rs)
auc_sr = roc_auc_score(y_true_r, pred_sr)
# Append scores and seed_dir
auc_scores_r.append(auc_r)
auc_scores_s.append(auc_s)
auc_scores_rs.append(auc_rs)
auc_scores_sr.append(auc_sr)
# Sort the scores
auc_scores_r.sort()
auc_scores_s.sort()
auc_scores_rs.sort()
auc_scores_sr.sort()
# Find median AUCs
median_auc_r = auc_scores_r[len(auc_scores_r) // 2] if auc_scores_r else None
median_auc_s = auc_scores_s[len(auc_scores_s) // 2] if auc_scores_s else None
median_auc_rs = auc_scores_rs[len(auc_scores_rs) //
2] if auc_scores_rs else None
median_auc_sr = auc_scores_sr[len(auc_scores_sr) //
2] if auc_scores_sr else None
return median_auc_r, median_auc_s, median_auc_rs, median_auc_sr
def get_permutations_aucs(
permutation_output_path: Path, sample_numbers: np.ndarray,
sample_types: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""Function to get the AUCs for all permutations.
Args:
permutation_output_path (Path): Path to the output directory containing
permutations saved results.
sample_numbers (np.ndarray): Sample numbers.
sample_types (np.ndarray): Sample types.
Returns:
Tuple[np.ndarray, np.ndarray]: AUCs for all
permutations for replica, section,
"""
# Get the unique sample numbers
unique_sample_numbers = np.unique(sample_numbers)
# Define arrays to store interpolated TPR values for each seed
aucs_r, aucs_s = [], []
# Loop through each seed and load the saved predictions
for seed_dir in permutation_output_path.glob("seed_*"):
if len(list(seed_dir.glob("*.npy"))) == 0:
continue
# Load predicted probabilities
pred_r = np.load(seed_dir / "predicted_probabilities_r.npy")
pred_s = np.load(seed_dir / "predicted_probabilities_s.npy")
# Load the permuted sample numbers and calculate the permuted WHO grades
permuted_sample_numbers_who_grades = np.load(
seed_dir / "permuted_sample_numbers_who_grades.npy"
)
who_grades_permuted = np.array(
[
permuted_sample_numbers_who_grades[np.where(
unique_sample_numbers == s_num
)[0][0]] for s_num in sample_numbers
]
)
# Get the permuted labels
y_permuted = (who_grades_permuted > 2).astype(int)
# Calculate ROC curves for each category
aucs_r.append(roc_auc_score(y_permuted[sample_types == 'replica'], pred_r))
aucs_s.append(roc_auc_score(y_permuted[sample_types == 'section'], pred_s))
return np.array(aucs_r), np.array(aucs_s)
def plot_permutation_dist(
permutation_auc_scores: np.ndarray, non_permuted_auc: float, ax: plt.Axes
) -> None:
"""
Plot the distribution of permutation AUC scores and save the plot.
Args:
permutation_auc_scores (np.ndarray): Array of AUC scores from the
permutation test.
non_permuted_auc (float): AUC score from the non-permuted data.
ax (plt.Axes): Axis to plot the permutation test histogram.
"""
# Calculate p-value
p_value = (np.sum(permutation_auc_scores >= non_permuted_auc) +
1) / (len(permutation_auc_scores) + 1)
# Determine the p-value significance text
if p_value < 0.0001:
p_text = "* * * *"
elif 0.0001 <= p_value < 0.001:
p_text = "* * *"
elif 0.001 <= p_value < 0.01:
p_text = "* *"
elif 0.01 <= p_value < 0.05:
p_text = "*"
else:
p_text = "ns"
# Plot the permutation test histogram
ax = sns.histplot(
permutation_auc_scores, bins=30, edgecolor='k', alpha=0.7,
label='Permutation AUCs', ax=ax, color="tab:blue", stat="count"
)