main.py 11.2 KB
Newer Older
1
import argparse
2

3
4
5
6
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
7
8

from dgl.dataloading import GraphDataLoader
9
from EEGGraphDataset import EEGGraphDataset
10
from joblib import dump, load
11
from sklearn import preprocessing
12
13
14
from sklearn.metrics import balanced_accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split
from torch.utils.data import WeightedRandomSampler
15

16
17
18
19
20
21
22
23
24
25

def _load_memory_mapped_array(file_name):
    # Due to a legacy problem related to memory alignment in joblib [1], the
    # data provided in the example may not be byte-aligned. This can be risky
    # when loading with mmap_mode. To fix the issue, load and re-dump the data.
    # [1] https://joblib.readthedocs.io/en/latest/developing.html#release-1-2-0
    dump(load(file_name), file_name)
    return load(file_name, mmap_mode="r")


26
27
if __name__ == "__main__":
    # argparse commandline args
28
29
30
31
32
33
34
35
36
37
38
39
    parser = argparse.ArgumentParser(
        description="Execute training pipeline on a given train/val subjects"
    )
    parser.add_argument(
        "--num_feats",
        type=int,
        default=6,
        help="Number of features per node for the graph",
    )
    parser.add_argument(
        "--num_nodes", type=int, default=8, help="Number of nodes in the graph"
    )
40
41
42
43
44
45
    parser.add_argument(
        "--num_workers",
        type=int,
        default=4,
        help="Number of epochs used to train",
    )
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
    parser.add_argument(
        "--gpu_idx",
        type=int,
        default=0,
        help="index of GPU device that should be used for this run, defaults to 0.",
    )
    parser.add_argument(
        "--num_epochs",
        type=int,
        default=40,
        help="Number of epochs used to train",
    )
    parser.add_argument(
        "--exp_name", type=str, default="default", help="Name for the test."
    )
    parser.add_argument(
        "--batch_size",
        type=int,
        default=512,
        help="Batch Size. Default is 512.",
    )
    parser.add_argument(
        "--model",
        type=str,
        default="shallow",
        help="type shallow to use shallow_EEGGraphDataset; "
        "type deep to use deep_EEGGraphDataset. Default is shallow",
    )
74
75
76
    args = parser.parse_args()

    # choose model
77
    if args.model == "shallow":
78
79
        from shallow_EEGGraphConvNet import EEGGraphConvNet

80
    if args.model == "deep":
81
82
83
84
85
86
87
88
        from deep_EEGGraphConvNet import EEGGraphConvNet

    # set the random seed so that we can reproduce the results
    np.random.seed(42)
    torch.manual_seed(42)

    # use GPU when available
    _GPU_IDX = args.gpu_idx
89
90
91
    _DEVICE = torch.device(
        f"cuda:{_GPU_IDX}" if torch.cuda.is_available() else "cpu"
    )
92
    torch.cuda.set_device(_DEVICE)
93
    print(f" Using device: {_DEVICE} {torch.cuda.get_device_name(_DEVICE)}")
94
95

    # load patient level indices
96
    _DATASET_INDEX = pd.read_csv("master_metadata_index.csv", low_memory=False)
97
98
99
100
101
102
103
104
105
    all_subjects = _DATASET_INDEX["patient_ID"].astype("str").unique()
    print(f"Subject list fetched! Total subjects are {len(all_subjects)}.")

    # retrieve inputs
    num_nodes = args.num_nodes
    _NUM_EPOCHS = args.num_epochs
    _EXPERIMENT_NAME = args.exp_name
    _BATCH_SIZE = args.batch_size
    num_feats = args.num_feats
106
    num_workers = args.num_workers
107
108

    # set up input and targets from files
109
110
    x = _load_memory_mapped_array(f"psd_features_data_X")
    y = _load_memory_mapped_array(f"labels_y")
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

    # normalize psd features data
    normd_x = []
    for i in range(len(y)):
        arr = x[i, :]
        arr = arr.reshape(1, -1)
        arr2 = preprocessing.normalize(arr)
        arr2 = arr2.reshape(48)
        normd_x.append(arr2)

    norm = np.array(normd_x)
    x = norm.reshape(len(y), 48)
    # map 0/1 to diseased/healthy
    label_mapping, y = np.unique(y, return_inverse=True)
    print(f"Unique labels 0/1 mapping: {label_mapping}")

    # split the dataset to train and test. The ratio of test is 0.3.
128
129
130
    train_and_val_subjects, heldout_subjects = train_test_split(
        all_subjects, test_size=0.3, random_state=42
    )
131
132
133

    # split the dataset using patient indices
    train_window_indices = _DATASET_INDEX.index[
134
135
        _DATASET_INDEX["patient_ID"].astype("str").isin(train_and_val_subjects)
    ].tolist()
136
    heldout_test_window_indices = _DATASET_INDEX.index[
137
138
        _DATASET_INDEX["patient_ID"].astype("str").isin(heldout_subjects)
    ].tolist()
139
140
141
142
143

    # define model, optimizer, scheduler
    model = EEGGraphConvNet(num_feats)
    loss_function = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
144
145
146
    scheduler = torch.optim.lr_scheduler.MultiStepLR(
        optimizer, milestones=[i * 10 for i in range(1, 26)], gamma=0.1
    )
147
148

    model = model.to(_DEVICE).double()
149
150
151
152
153
154
    num_trainable_params = np.sum(
        [
            np.prod(p.size()) if p.requires_grad else 0
            for p in model.parameters()
        ]
    )
155
156
157
158
159
160
161
162
163
164
165
166
167

    # Dataloader========================================================================================================

    # use WeightedRandomSampler to balance the training dataset

    labels_unique, counts = np.unique(y, return_counts=True)

    class_weights = np.array([1.0 / x for x in counts])
    # provide weights for samples in the training set only
    sample_weights = class_weights[y[train_window_indices]]
    # sampler needs to come up with training set size number of samples
    weighted_sampler = WeightedRandomSampler(
        weights=sample_weights,
168
169
        num_samples=len(train_window_indices),
        replacement=True,
170
171
172
173
174
175
176
177
    )

    # train data loader
    train_dataset = EEGGraphDataset(
        x=x, y=y, num_nodes=num_nodes, indices=train_window_indices
    )

    train_loader = GraphDataLoader(
178
179
        dataset=train_dataset,
        batch_size=_BATCH_SIZE,
180
        sampler=weighted_sampler,
181
        num_workers=num_workers,
182
        pin_memory=True,
183
184
185
186
    )

    # this loader is used without weighted sampling, to evaluate metrics on full training set after each epoch
    train_metrics_loader = GraphDataLoader(
187
188
189
        dataset=train_dataset,
        batch_size=_BATCH_SIZE,
        shuffle=False,
190
        num_workers=num_workers,
191
        pin_memory=True,
192
193
194
195
196
197
198
199
    )

    # test data loader
    test_dataset = EEGGraphDataset(
        x=x, y=y, num_nodes=num_nodes, indices=heldout_test_window_indices
    )

    test_loader = GraphDataLoader(
200
201
202
        dataset=test_dataset,
        batch_size=_BATCH_SIZE,
        shuffle=False,
203
        num_workers=num_workers,
204
        pin_memory=True,
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
    )

    auroc_train_history = []
    auroc_test_history = []
    balACC_train_history = []
    balACC_test_history = []
    loss_train_history = []
    loss_test_history = []

    # training=========================================================================================================
    for epoch in range(_NUM_EPOCHS):
        model.train()
        train_loss = []

        for batch_idx, batch in enumerate(train_loader):
            # send batch to GPU
            g, dataset_idx, y = batch
            g_batch = g.to(device=_DEVICE, non_blocking=True)
            y_batch = y.to(device=_DEVICE, non_blocking=True)
            optimizer.zero_grad()

            # forward pass
            outputs = model(g_batch)
            loss = loss_function(outputs, y_batch)
            train_loss.append(loss.item())

            # backward pass
            loss.backward()
            optimizer.step()

        # update learning rate
        scheduler.step()

238
        # evaluate model after each epoch for train-metric data============================================================
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        model.eval()
        with torch.no_grad():
            y_probs_train = torch.empty(0, 2).to(_DEVICE)
            y_true_train, y_pred_train = [], []

            for i, batch in enumerate(train_metrics_loader):
                g, dataset_idx, y = batch
                g_batch = g.to(device=_DEVICE, non_blocking=True)
                y_batch = y.to(device=_DEVICE, non_blocking=True)

                # forward pass
                outputs = model(g_batch)

                _, predicted = torch.max(outputs.data, 1)
                y_pred_train += predicted.cpu().numpy().tolist()
                # concatenate along 0th dimension
                y_probs_train = torch.cat((y_probs_train, outputs.data), 0)
                y_true_train += y_batch.cpu().numpy().tolist()

        # returning prob distribution over target classes, take softmax over the 1st dimension
259
260
261
        y_probs_train = (
            nn.functional.softmax(y_probs_train, dim=1).cpu().numpy()
        )
262
263
        y_true_train = np.array(y_true_train)

264
        # evaluate model after each epoch for validation data ==============================================================
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        y_probs_test = torch.empty(0, 2).to(_DEVICE)
        y_true_test, minibatch_loss, y_pred_test = [], [], []

        for i, batch in enumerate(test_loader):
            g, dataset_idx, y = batch
            g_batch = g.to(device=_DEVICE, non_blocking=True)
            y_batch = y.to(device=_DEVICE, non_blocking=True)

            # forward pass
            outputs = model(g_batch)
            _, predicted = torch.max(outputs.data, 1)
            y_pred_test += predicted.cpu().numpy().tolist()

            loss = loss_function(outputs, y_batch)
            minibatch_loss.append(loss.item())
            y_probs_test = torch.cat((y_probs_test, outputs.data), 0)
            y_true_test += y_batch.cpu().numpy().tolist()

        # returning prob distribution over target classes, take softmax over the 1st dimension
284
285
286
        y_probs_test = (
            torch.nn.functional.softmax(y_probs_test, dim=1).cpu().numpy()
        )
287
288
289
        y_true_test = np.array(y_true_test)

        # record training auroc and testing auroc
290
291
292
293
294
295
        auroc_train_history.append(
            roc_auc_score(y_true_train, y_probs_train[:, 1])
        )
        auroc_test_history.append(
            roc_auc_score(y_true_test, y_probs_test[:, 1])
        )
296
297

        # record training balanced accuracy and testing balanced accuracy
298
299
300
301
302
303
        balACC_train_history.append(
            balanced_accuracy_score(y_true_train, y_pred_train)
        )
        balACC_test_history.append(
            balanced_accuracy_score(y_true_test, y_pred_test)
        )
304
305
306
307
308
309

        # LOSS - epoch loss is defined as mean of minibatch losses within epoch
        loss_train_history.append(np.mean(train_loss))
        loss_test_history.append(np.mean(minibatch_loss))

        # print the metrics
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        print(
            "Train loss: {}, test loss: {}".format(
                loss_train_history[-1], loss_test_history[-1]
            )
        )
        print(
            "Train AUC: {}, test AUC: {}".format(
                auroc_train_history[-1], auroc_test_history[-1]
            )
        )
        print(
            "Train Bal.ACC: {}, test Bal.ACC: {}".format(
                balACC_train_history[-1], balACC_test_history[-1]
            )
        )
325
326
327

        # save model from each epoch====================================================================================
        state = {
328
329
330
331
332
            "epochs": _NUM_EPOCHS,
            "experiment_name": _EXPERIMENT_NAME,
            "model_description": str(model),
            "state_dict": model.state_dict(),
            "optimizer": optimizer.state_dict(),
333
334
        }
        torch.save(state, f"{_EXPERIMENT_NAME}_Epoch_{epoch}.ckpt")