Switch to unified view

a b/examples/tcga_lung/latefusion.py
1
import argparse
2
import inspect
3
import os
4
import sys
5
6
# import warnings
7
from datetime import datetime
8
9
import numpy as np
10
import pandas as pd
11
from joblib import delayed
12
from sklearn.base import clone
13
from sklearn.model_selection import StratifiedKFold
14
from sklearn.utils import check_random_state
15
from tqdm import tqdm
16
17
from _init_scripts_tcga import PredictionTask
18
from _utils import read_yaml, write_yaml, ProgressParallel
19
20
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
21
parentdir = os.path.dirname(os.path.dirname(currentdir))
22
sys.path.insert(0, parentdir)
23
24
from multipit.multi_model.latefusion import LateFusionClassifier
25
26
27
def main(params):
28
    """
29
    Repeated cross-validation experiment for classification with late fusion
30
    """
31
32
    # Uncomment for disabling ConvergenceWarning
33
    # warnings.simplefilter("ignore")
34
    # os.environ["PYTHONWARNINGS"] = 'ignore'
35
36
    # 0. Read config file and save it in the results
37
    config = read_yaml(params.config)
38
    save_name = config["save_name"]
39
    if save_name is None:
40
        run_id = datetime.now().strftime(r"%m%d_%H%M%S")
41
        save_name = "exp_" + run_id
42
    save_dir = os.path.join(params.save_path, save_name)
43
    os.mkdir(save_dir)
44
    write_yaml(config, os.path.join(save_dir, "config.yaml"))
45
46
    # 1. fix random seeds for reproducibility
47
    seed = config["latefusion"]["seed"]
48
    np.random.seed(seed)
49
50
    # 2. Load data and define pipelines for each modality
51
    ptask = PredictionTask(config, survival=False, integration="late")
52
    ptask.load_data()
53
    X, y = ptask.data_concat.values, ptask.labels.loc[ptask.data_concat.index].values
54
    ptask.init_pipelines_latefusion()
55
56
    # 3. Perform repeated cross-validation
57
    parallel = ProgressParallel(
58
        n_jobs=config["parallelization"]["n_jobs_repeats"],
59
        total=config["latefusion"]["n_repeats"],
60
    )
61
    results_parallel = parallel(
62
        delayed(_fun_repeats)(
63
            ptask,
64
            X,
65
            y,
66
            r,
67
            disable_infos=(config["parallelization"]["n_jobs_repeats"] is not None)
68
            and (config["parallelization"]["n_jobs_repeats"] > 1),
69
        )
70
        for r in range(config["latefusion"]["n_repeats"])
71
    )
72
73
    # 4. Save results
74
    if config["permutation_test"]:
75
        perm_predictions = np.zeros(
76
            (
77
                len(y),
78
                len(ptask.names),
79
                config["n_permutations"],
80
                config["latefusion"]["n_repeats"],
81
            )
82
        )
83
        list_data_preds= []
84
        for p, res in enumerate(results_parallel):
85
            list_data_preds.append(res[0])
86
            perm_predictions[:, :, :, p] = res[1]
87
        perm_labels = results_parallel[-1][3]
88
89
        np.save(os.path.join(save_dir, "permutation_labels.npy"), perm_labels)
90
        np.save(os.path.join(save_dir, "permutation_predictions.npy"), perm_predictions)
91
        data_preds = pd.concat(list_data_preds, axis=0)
92
        data_preds.to_csv(os.path.join(save_dir, "predictions.csv"))
93
    else:
94
        list_data_preds = []
95
        for p, res in enumerate(results_parallel):
96
            list_data_preds.append(res[0])
97
        data_preds = pd.concat(list_data_preds, axis=0)
98
        data_preds.to_csv(os.path.join(save_dir, "predictions.csv"))
99
100
101
def _fun_repeats(prediction_task, X, y, r, disable_infos):
102
    """
103
    Train and test a late fusion model for classification with cross-validation
104
105
    Parameters
106
    ----------
107
    prediction_task: PredictionTask object
108
109
    X: 2D array of shape (n_samples, n_features)
110
        Concatenation of the different modalities
111
112
    y: 1D array of shape (n_samples,)
113
        Binary outcome
114
115
    r: int
116
        Repeat number
117
118
    disable_infos: bool
119
120
    Returns
121
    -------
122
    df_pred: pd.DataFrame of shape (n_samples, n_models+3)
123
        Predictions collected over the test sets of the cross-validation scheme for each multimodal combination
124
125
    df_thrs: pd.DataFrame of shape (n_samples, n_models+2), None
126
        Thresholds that optimize the log-rank test on the training set for each fold and each multimodal combination.
127
128
    permut_predictions: 3D array of shape (n_samples, n_models, n_permutations)
129
        Predictions collected over the test sets of the cross_validation scheme for each multimodal combination and each random permutation of the labels.
130
131
    permut_labels: 2D array of shape (n_samples, n_permutations)
132
        Permuted labels
133
    """
134
    cv = StratifiedKFold(n_splits=10, shuffle=True)  # , random_state=np.random.seed(i))
135
    X_preds = np.zeros((len(y), 3 + len(prediction_task.names)))
136
137
    late_clf = LateFusionClassifier(
138
        estimators=prediction_task.late_estimators,
139
        cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=np.random.seed(r)),
140
        **prediction_task.config["latefusion"]["args"]
141
    )
142
143
    # 1. Cross-validation scheme
144
    for fold_index, (train_index, test_index) in tqdm(
145
        enumerate(cv.split(np.zeros(len(y)), y)),
146
        leave=False,
147
        total=cv.get_n_splits(np.zeros(len(y))),
148
        disable=disable_infos,
149
    ):
150
        X_train, y_train, X_test = (
151
            X[train_index, :],
152
            y[train_index],
153
            X[test_index, :],
154
        )
155
156
        # Fit late fusion on the training set of the fold
157
        clf = clone(late_clf)
158
        clf.fit(X_train, y_train)
159
        # Collect predictions on the test set of the fold for each multimodal combination
160
        for c, idx in enumerate(prediction_task.indices):
161
            X_preds[test_index, c] = clf.predict_proba(X_test, estim_ind=idx)[:, 1]
162
163
        X_preds[test_index, -3] = fold_index
164
165
    X_preds[:, -2] = r
166
    X_preds[:, -1] = y
167
168
    df_pred = (
169
        pd.DataFrame(
170
            X_preds,
171
            columns=prediction_task.names + ["fold_index", "repeat", "label"],
172
            index=prediction_task.data_concat.index,
173
        )
174
        .reset_index()
175
        .rename(columns={"bcr_patient_barcode": "samples"})
176
        .set_index(["repeat", "samples"])
177
    )
178
179
    # 2. Perform permutation test
180
    permut_predictions = None
181
    permut_labels = None
182
    if prediction_task.config["permutation_test"]:
183
        permut_labels = np.zeros((len(y), prediction_task.config["n_permutations"]))
184
        permut_predictions = np.zeros(
185
            (
186
                len(y),
187
                len(prediction_task.names),
188
                prediction_task.config["n_permutations"],
189
            )
190
        )
191
        for prm in range(prediction_task.config["n_permutations"]):
192
            X_perm = np.zeros((len(y), len(prediction_task.names)))
193
            random_state = check_random_state(prm)
194
            sh_ind = random_state.permutation(len(y))
195
            yshuffle = np.copy(y)[sh_ind]
196
            permut_labels[:, prm] = yshuffle
197
            for fold_index, (train_index, test_index) in tqdm(
198
                enumerate(cv.split(np.zeros(len(y)), y)),
199
                leave=False,
200
                total=cv.get_n_splits(np.zeros(len(y))),
201
                disable=disable_infos,
202
            ):
203
                X_train, yshuffle_train, X_test = (
204
                    X[train_index, :],
205
                    yshuffle[train_index],
206
                    X[test_index, :],
207
                )
208
                clf = clone(late_clf)
209
                clf.fit(X_train, yshuffle_train)
210
211
                for c, idx in enumerate(prediction_task.indices):
212
                    X_perm[test_index, c] = clf.predict_proba(X_test, estim_ind=idx)[
213
                        :, 1
214
                    ]
215
            permut_predictions[:, :, prm] = X_perm
216
    return df_pred, permut_predictions, permut_labels
217
218
219
if __name__ == "__main__":
220
    args = argparse.ArgumentParser(description="Late fusion")
221
    args.add_argument(
222
        "-c",
223
        "--config",
224
        type=str,
225
        help="config file path",
226
    )
227
    args.add_argument(
228
        "-s",
229
        "--save_path",
230
        type=str,
231
        help="save path",
232
    )
233
    main(params=args.parse_args())