training.py 13.4 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
from split import train_test_indexes_patient_wise
Alessia Marcolini's avatar
Alessia Marcolini committed
30
from config import get_project_root
Alessia Marcolini's avatar
Alessia Marcolini committed
31

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

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

Alessia Marcolini's avatar
Alessia Marcolini committed
43
PRETRAINED_MED3D_WEIGHTS = PROJECT_ROOT / 'pretrained_weights' / 'resnet_50.pth'
44
45
46
47
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

settings = {
    "model": CiompiDO,
    "batch_size": 16,
    "lr": 1e-5,
Alessia Marcolini's avatar
Alessia Marcolini committed
53
    "epochs": 1,
Alessia Marcolini's avatar
Alessia Marcolini committed
54
55
56
57
58
59
60
61
62
63
    "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):
Alessia Marcolini's avatar
Alessia Marcolini committed
89
    log_dir = PROJECT_ROOT / "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

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

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

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

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

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

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

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

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

163
_, class_sample_count = np.unique(labels_train, return_counts=True)
Alessia Marcolini's avatar
Alessia Marcolini committed
164
165
n_max = np.max(class_sample_count)
weights = n_max / class_sample_count
Alessia Marcolini's avatar
Alessia Marcolini committed
166
weights = torch.Tensor(weights).to(device)
167
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
168
169
170
171
172
173
174
# ### 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
175
176
# %%
# model.initialize_weights()
Alessia Marcolini's avatar
Alessia Marcolini committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

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(
196
197
198
        EXPERIMENT_DIR
        / 'Tstage_grouped_noTx_CT_valieres_20191029-173736'
        / 'checkpoint_290.pth'
Alessia Marcolini's avatar
Alessia Marcolini committed
199
200
    )
    pretrained_PT_dict = torch.load(
201
202
203
        EXPERIMENT_DIR
        / 'Tstage_grouped_noTx_PET_valieres_20191029-195338'
        / 'checkpoint_290.pth'
Alessia Marcolini's avatar
Alessia Marcolini committed
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
    )

    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])

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

257
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# ### 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(),
275
            EXPERIMENT_DIR / EXPERIMENT_NAME / f'checkpoint_{epoch}.pth',
Alessia Marcolini's avatar
Alessia Marcolini committed
276
277
278
279
280
281
282
283
284
285
286
287
        )

    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)
288
        labels_tr = torch.LongTensor(data["target"]).to(device)
Alessia Marcolini's avatar
Alessia Marcolini committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        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)
308
                    labels_ts = torch.LongTensor(data_test["target"]).to(device)
Alessia Marcolini's avatar
Alessia Marcolini committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322

                    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()

323
324
                # TODO: fix best model check

Alessia Marcolini's avatar
Alessia Marcolini committed
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
                # 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"],
            )
        )

356
357
# %%
### Predict on Train
Alessia Marcolini's avatar
Alessia Marcolini committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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)
375
        trues_tr.append(label)
Alessia Marcolini's avatar
Alessia Marcolini committed
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
        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),
]


400
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# ### 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())
417
        trues_ts.append(label)
Alessia Marcolini's avatar
Alessia Marcolini committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
        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)]

435
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
436
437
438
# ## Save results

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

# Save losses
losses_tr = np.array(losses_tr)
losses_vl = np.array(losses_ts)
445
446
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
447

448
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
449
450
451
452
453
454
# Plot losses

plt.figure(figsize=(20, 10))
plt.plot(losses_tr, color="blue")
plt.plot(losses_ts, color="orange")
plt.legend(["train", "valid"])
455
plt.savefig(EXPERIMENT_DIR / EXPERIMENT_NAME / 'losses.png', close=True, verbose=True)
Alessia Marcolini's avatar
Alessia Marcolini committed
456
plt.close()
457
# %%
Alessia Marcolini's avatar
Alessia Marcolini committed
458
# Save predictions, ground truth, probabilities and filenames
459
460
461
462
463
464
465
466
467
468
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
469
470
471
472
473
474
# Save metrics
metrics_out = pd.DataFrame(
    (train_metrics, test_metrics),
    columns=["MCC", "ACC", "prec", "rec"],
    index=["train", "test"],
)
475
metrics_out.to_csv(EXPERIMENT_DIR / EXPERIMENT_NAME / 'metrics_out.csv')
Alessia Marcolini's avatar
Alessia Marcolini committed
476
477
478


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