training.py 13.3 KB
Newer Older
1
2
3
#%% [markdown]
# ## Training network for feature extraction
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
4
5
import datetime
import gc
6
import os
Alessia Marcolini's avatar
Alessia Marcolini committed
7
8
9
import pickle
import sys
import time
10
11
12
from pathlib import Path

# os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
Alessia Marcolini's avatar
Alessia Marcolini committed
13

14
import matplotlib.pyplot as plt
Alessia Marcolini's avatar
Alessia Marcolini committed
15
16
17
18
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
19
20
21
22
23
from sklearn.metrics import accuracy_score as acc
from sklearn.metrics import confusion_matrix
from sklearn.metrics import matthews_corrcoef as mcor
from sklearn.metrics import precision_score as precision
from sklearn.metrics import recall_score as recall
Alessia Marcolini's avatar
Alessia Marcolini committed
24
25
26
27
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from dataset import NumpyCSVDataset, augment_3D_HN
28
from networks import CiompiDO, ResNet50_3d
Alessia Marcolini's avatar
Alessia Marcolini committed
29
30
from split import train_test_indexes_patient_wise

31
32
33
PATH = Path(os.getcwd())
print(PATH)
#%%
Alessia Marcolini's avatar
Alessia Marcolini committed
34
35
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
multigpu = True
Alessia Marcolini's avatar
Alessia Marcolini committed
36
#
37
38
DATASET = 'HN_val'
BBOX_SUBDATASET = 'bbox_64'
Alessia Marcolini's avatar
Alessia Marcolini committed
39

40
DATASET_DIR = PATH / 'data' / DATASET / 'processed' / 'bbox' / BBOX_SUBDATASET
Alessia Marcolini's avatar
Alessia Marcolini committed
41
EXPERIMENT_DIR = PATH / 'experiments'
Alessia Marcolini's avatar
Alessia Marcolini committed
42

43
44
45
46
47
PRETRAINED_MED3D_WEIGHTS = PATH / 'pretrained_weights' / 'resnet_50.pth'
PRETRAINED_T_STAGE = EXPERIMENT_DIR / 'Tstage_4_noTx_CT_20191114-163418' / 'weights.pth'
# %%
### Settings
EXPERIMENT_NAME = "prova" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
Alessia Marcolini's avatar
Alessia Marcolini committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

settings = {
    "model": CiompiDO,
    "batch_size": 16,
    "lr": 1e-5,
    "epochs": 300,
    "optim": torch.optim.Adam,
    "K": 0.2,
    "n_classes": 4,  # TSTAGE
    "seed": 1234,
    "dropout": 0.5,
    "split": "8020",
    "size": 64,
    "pretrained": "",
}

64
assert settings["split"] in ["vallieres", "8020"]
Alessia Marcolini's avatar
Alessia Marcolini committed
65
assert not settings["split"] == "vallieres" or DATASET == 'HN_val'
Alessia Marcolini's avatar
Alessia Marcolini committed
66
67
assert settings["pretrained"] in ["Med3D", "branch-wise", "T-stage", ""]

68
69
os.makedirs(EXPERIMENT_DIR / EXPERIMENT_NAME, exist_ok=False)
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
MODEL = settings["model"]
BATCH_SIZE = settings["batch_size"]
LR = settings["lr"]
EPOCHS = settings["epochs"]
OPTIMIZER = settings["optim"]
K = settings["K"]
N_CLASSES = settings["n_classes"]
SEED = settings["seed"]
DROPOUT = settings["dropout"]
SPLIT = settings["split"]
SIZE = settings["size"]
PRETRAINED = settings["pretrained"]


84
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
85
86
87
88
# ### Tensorboard settings


def new_run_log_dir(experiment_name):
89
    log_dir = PATH / "tb-runs"
Alessia Marcolini's avatar
Alessia Marcolini committed
90
91
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
92
    run_log_dir = log_dir / experiment_name
Alessia Marcolini's avatar
Alessia Marcolini committed
93
94
95
96
97
98
99
    return run_log_dir


log_dir = new_run_log_dir(EXPERIMENT_NAME)
print(f"Tensorboard folder: {log_dir}")

writer = SummaryWriter(log_dir)
100
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
101
102
# ### Data Handlers

103
clinical_file = PATH / 'data' / DATASET / 'processed' / f'clinical_{DATASET}.csv'
Alessia Marcolini's avatar
Alessia Marcolini committed
104
target_column = "T-stage_grouped"
105
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
106
107
np.random.seed(SEED)

108
109
dataset_train = NumpyCSVDataset(
    data_dir=DATASET_DIR,
Alessia Marcolini's avatar
Alessia Marcolini committed
110
    clinical_file=clinical_file,
111
112
113
114
115
    label_col=target_column,
    size=SIZE,
    mode='train',
    seed=SEED,
)
Alessia Marcolini's avatar
Alessia Marcolini committed
116

117
118
dataset_test = NumpyCSVDataset(
    data_dir=DATASET_DIR,
Alessia Marcolini's avatar
Alessia Marcolini committed
119
    clinical_file=clinical_file,
120
121
122
123
124
125
    label_col=target_column,
    size=SIZE,
    mode='test',
    seed=SEED,
)
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
126
# Create train-test datasets
127
if SPLIT == "vallieres":
Alessia Marcolini's avatar
Alessia Marcolini committed
128
129
    idx_train = [
        i
130
        for i, f in enumerate(dataset_train.patients)
Alessia Marcolini's avatar
Alessia Marcolini committed
131
132
133
134
135
        if f.split("-")[1] in ["CHUS", "HGJ"]
    ]

    idx_test = [
        i
136
        for i, f in enumerate(dataset_test.patients)
Alessia Marcolini's avatar
Alessia Marcolini committed
137
138
139
140
141
        if f.split("-")[1] in ["HMR", "CHUM"]
    ]

else:
    idx_train, idx_test = train_test_indexes_patient_wise(
142
        dataset_train, test_size=K, stratify=True
Alessia Marcolini's avatar
Alessia Marcolini committed
143
144
    )

145
146
147
dataset_train.indices = np.array(idx_train)
dataset_test.indices = np.array(idx_test)
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
148
149
150
151
152
# Create loaders
loader_train = DataLoader(
    dataset_train, batch_size=BATCH_SIZE, num_workers=12, pin_memory=True, shuffle=True
)

153
154
155
loader_test = DataLoader(
    dataset_test, batch_size=BATCH_SIZE, num_workers=12, shuffle=False
)
Alessia Marcolini's avatar
Alessia Marcolini committed
156

157
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
158
# Compute weights only on training set
159
labels_train = dataset_train.labels
Alessia Marcolini's avatar
Alessia Marcolini committed
160

161
_, class_sample_count = np.unique(labels_train, return_counts=True)
Alessia Marcolini's avatar
Alessia Marcolini committed
162
163
n_max = np.max(class_sample_count)
weights = n_max / class_sample_count
Alessia Marcolini's avatar
Alessia Marcolini committed
164
weights = torch.Tensor(weights).to(device)
165
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
166
167
168
169
170
171
172
# ### Initialize Model

model = MODEL(n_classes=N_CLASSES, n_channels=2, modality="CT/PET", dropout=DROPOUT)

if multigpu:
    model = nn.DataParallel(model.to(device))
    model = model.module
173
174
# %%
# model.initialize_weights()
Alessia Marcolini's avatar
Alessia Marcolini committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

if PRETRAINED == "Med3D":
    pretrained_dict = torch.load(PRETRAINED_MED3D_WEIGHTS)["state_dict"]
    model_dict = model.state_dict()

    # discard layers not present in destination network or with different shape
    pretrained_dict = {
        k: v
        for k, v in pretrained_dict.items()
        if (k in model_dict) and (model_dict[k].shape == pretrained_dict[k].shape)
    }

    for name in model.state_dict().keys():
        if name in pretrained_dict.keys():
            # print(name)
            model.state_dict()[name].copy_(pretrained_dict[name])

elif PRETRAINED == "branch-wise":
    pretrained_CT_dict = torch.load(
194
195
196
        EXPERIMENT_DIR
        / 'Tstage_grouped_noTx_CT_valieres_20191029-173736'
        / 'checkpoint_290.pth'
Alessia Marcolini's avatar
Alessia Marcolini committed
197
198
    )
    pretrained_PT_dict = torch.load(
199
200
201
        EXPERIMENT_DIR
        / 'Tstage_grouped_noTx_PET_valieres_20191029-195338'
        / 'checkpoint_290.pth'
Alessia Marcolini's avatar
Alessia Marcolini committed
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
    )

    model_dict = model.state_dict()

    pretrained_CT_dict = {
        k: v
        for k, v in pretrained_CT_dict.items()
        if (k in model_dict) and (model_dict[k].shape == pretrained_CT_dict[k].shape)
    }

    pretrained_PT_dict = {
        k: v
        for k, v in pretrained_PT_dict.items()
        if (k in model_dict) and (model_dict[k].shape == pretrained_PT_dict[k].shape)
    }

    to_add = "module." if multigpu else ""

    for name in model.CT_branch.state_dict().keys():
        name_complete = to_add + "CT_branch." + name
        # print(name_complete)
        if name_complete in pretrained_CT_dict.keys():
            print(name)
            model.CT_branch.state_dict()[name].copy_(pretrained_CT_dict[name_complete])

    for name in model.PT_branch.state_dict().keys():
        name_complete = to_add + "PT_branch." + name
        # print(name_complete)
        if name_complete in pretrained_PT_dict.keys():
            print(name)
            model.PT_branch.state_dict()[name].copy_(pretrained_PT_dict[name_complete])

elif PRETRAINED == "T-stage":
    pretrained_dict = torch.load(PRETRAINED_T_STAGE)
    model_dict = model.state_dict()

    # discard layers not present in destination network or with different shape
    pretrained_dict = {
        k: v
        for k, v in pretrained_dict.items()
        if (k in model_dict) and (model_dict[k].shape == pretrained_dict[k].shape)
    }

    for name in model.state_dict().keys():
        if name in pretrained_dict.keys():
            # print(name)
            model.state_dict()[name].copy_(pretrained_dict[name])

250
251
252
# %%
# Optimizer and criterion
optimizer = OPTIMIZER(model.parameters(), lr=LR)
Alessia Marcolini's avatar
Alessia Marcolini committed
253
254
criterion = nn.CrossEntropyLoss(weight=weights)

255
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# ### Train
model.train()  # Set model to training mode

global_i = 0

losses_tr = []
losses_ts = []

last_loss_test = -1
iteration = 0
start_time = time.time()

for epoch in range(EPOCHS):
    # print(epoch)
    if epoch % 10 == 0:  # save checkpoint
        torch.save(
            model.state_dict(),
273
            EXPERIMENT_DIR / EXPERIMENT_NAME / f'checkpoint_{epoch}.pth',
Alessia Marcolini's avatar
Alessia Marcolini committed
274
275
276
277
278
279
280
281
282
283
284
285
        )

    for j, data in enumerate(loader_train):
        global_i += 1

        if j % 10 == 0:
            print(time.time() - start_time)
            start_time = time.time()

        optimizer.zero_grad()

        images_tr = data["data"].to(device)
286
        labels_tr = torch.LongTensor(data["target"]).to(device)
Alessia Marcolini's avatar
Alessia Marcolini committed
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        outputs_tr = model(images_tr).to(device)

        # backward
        loss = criterion(outputs_tr, labels_tr)
        loss.backward()

        optimizer.step()

        # check test set
        if j % int(len(loader_train) / 2) == 0 and j != 0:
            model.eval()
            with torch.no_grad():

                losses_sum = 0
                num_samples_test = 0

                for data_test in loader_test:

                    images_ts = data_test["data"].to(device)
306
                    labels_ts = torch.LongTensor(data_test["target"]).to(device)
Alessia Marcolini's avatar
Alessia Marcolini committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320

                    outputs_ts = model.forward(images_ts)

                    loss_test_sum = criterion(outputs_ts, labels_ts).item()
                    losses_sum += loss_test_sum
                    num_samples_test += 1

                loss_test_avg = losses_sum / num_samples_test

                writer.add_scalar(
                    f"{EXPERIMENT_NAME}/test_loss", loss_test_avg, global_i
                )
                writer.flush()

321
322
                # TODO: fix best model check

Alessia Marcolini's avatar
Alessia Marcolini committed
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
                # is_best = loss_val_avg < last_loss_val
                # if is_best:
                #    torch.save(model.state_dict(),
                #               f'{EXPERIMENT_DIR}/{EXPERIMENT_NAME}/checkpoint_best_{epoch}.pth')

                last_loss_test = loss_test_avg

            losses_tr.append(loss.item())
            losses_ts.append(loss_test_avg)

            del images_ts, labels_ts

        iteration += 1
        del images_tr, labels_tr
        gc.collect()
        model.train()

        # sys.stdout.write
        writer.add_scalar(f"{EXPERIMENT_NAME}/train_loss", loss.item(), global_i)
        writer.flush()
        sys.stdout.write(
            "\r Epoch {} of {}  [{:.2f}%] - loss TR/TS: {:.4f} / {:.4f} - {}".format(
                epoch + 1,
                EPOCHS,
                100 * j / len(loader_train),
                loss.item(),
                last_loss_test,
                optimizer.param_groups[0]["lr"],
            )
        )

354
355
# %%
### Predict on Train
Alessia Marcolini's avatar
Alessia Marcolini committed
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
model.eval()
dataset_train.mode = "test"  # no augmentation

preds_tr = []
trues_tr = []
probs_tr = []
filenames_tr = []

with torch.no_grad():
    for data in dataset_train:
        image = data["data"].unsqueeze(0).to(device)
        label = data["target"]
        output = model(image)  # forward
        _, pred = torch.max(output, 1)

        preds_tr.append(pred.data.cpu().numpy())
        #         trues.append(label)
373
        trues_tr.append(label)
Alessia Marcolini's avatar
Alessia Marcolini committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        probs_tr.append(output.data.cpu().numpy())
        filenames_tr.append(data["filename"])

probs_tr = np.concatenate(probs_tr)
preds_tr = np.concatenate(preds_tr)
trues_tr = np.array(trues_tr)
filenames_tr = np.array(filenames_tr)

MCC_tr = mcor(trues_tr, preds_tr)
ACC_tr = acc(trues_tr, preds_tr)
prec_tr = precision(trues_tr, preds_tr, average="weighted")
rec_tr = recall(trues_tr, preds_tr, average="weighted")

print("MCC train", round(MCC_tr, 3), "ACC train", round(ACC_tr, 3))
print("precision train", round(prec_tr, 3), "recall train", round(rec_tr, 3))

train_metrics = [
    round(MCC_tr, 3),
    round(ACC_tr, 3),
    round(prec_tr, 3),
    round(rec_tr, 3),
]


398
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# ### Predict on Test
model.eval()

preds_ts = []
trues_ts = []
probs_ts = []
filenames_ts = []

with torch.no_grad():
    for data in dataset_test:
        image = data["data"].unsqueeze(0).to(device)
        label = data["target"]
        output = model(image)  # forward
        _, pred = torch.max(output, 1)

        preds_ts.append(pred.data.cpu().numpy())
415
        trues_ts.append(label)
Alessia Marcolini's avatar
Alessia Marcolini committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
        probs_ts.append(output.data.cpu().numpy())
        filenames_ts.append(data["filename"])

probs_ts = np.concatenate(probs_ts)
preds_ts = np.concatenate(preds_ts)
trues_ts = np.array(trues_ts)
filenames_ts = np.array(filenames_ts)

MCC_ts = mcor(trues_ts, preds_ts)
ACC_ts = acc(trues_ts, preds_ts)
prec_ts = precision(trues_ts, preds_ts, average="weighted")
rec_ts = recall(trues_ts, preds_ts, average="weighted")

print("MCC test", round(MCC_ts, 3), "ACC test", round(ACC_ts, 3))
print("precision test", round(prec_ts, 3), "recall test", round(rec_ts, 3))
test_metrics = [round(MCC_ts, 3), round(ACC_ts, 3), round(prec_ts, 3), round(rec_ts, 3)]

433
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
434
435
436
# ## Save results

# Save settings
437
with open(EXPERIMENT_DIR / EXPERIMENT_NAME / 'settings.pkl', 'wb') as f:
Alessia Marcolini's avatar
Alessia Marcolini committed
438
439
440
441
442
    pickle.dump(settings, f, pickle.HIGHEST_PROTOCOL)

# Save losses
losses_tr = np.array(losses_tr)
losses_vl = np.array(losses_ts)
443
444
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'losses_tr.npy', losses_tr)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'losses_ts.npy', losses_vl)
Alessia Marcolini's avatar
Alessia Marcolini committed
445

446
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
447
448
449
450
451
452
# Plot losses

plt.figure(figsize=(20, 10))
plt.plot(losses_tr, color="blue")
plt.plot(losses_ts, color="orange")
plt.legend(["train", "valid"])
453
plt.savefig(EXPERIMENT_DIR / EXPERIMENT_NAME / 'losses.png', close=True, verbose=True)
Alessia Marcolini's avatar
Alessia Marcolini committed
454
plt.close()
455
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
456
# Save predictions, ground truth, probabilities and filenames
457
458
459
460
461
462
463
464
465
466
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'preds_tr.npy', preds_tr)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'trues_tr.npy', trues_tr)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'probs_tr.npy', probs_tr)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'filenames_tr.npy', filenames_tr)

np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'preds_ts.npy', preds_ts)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'trues_ts.npy', trues_ts)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'probs_ts.npy', probs_ts)
np.save(EXPERIMENT_DIR / EXPERIMENT_NAME / 'filenames_ts.npy', filenames_ts)
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
467
468
469
470
471
472
# Save metrics
metrics_out = pd.DataFrame(
    (train_metrics, test_metrics),
    columns=["MCC", "ACC", "prec", "rec"],
    index=["train", "test"],
)
473
metrics_out.to_csv(EXPERIMENT_DIR / EXPERIMENT_NAME / 'metrics_out.csv')
Alessia Marcolini's avatar
Alessia Marcolini committed
474
475
476


# Save model weights
477
torch.save(model.state_dict(), EXPERIMENT_DIR / EXPERIMENT_NAME / 'weights.pth')
Alessia Marcolini's avatar
Alessia Marcolini committed
478
# %%