-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_train_diffunet_brats2023.py
170 lines (122 loc) · 5.53 KB
/
3_train_diffunet_brats2023.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
import numpy as np
from light_training.dataloading.dataset import get_train_test_loader_from_test_list
import torch
import torch.nn as nn
from monai.inferers import SlidingWindowInferer
from light_training.evaluation.metric import dice
from light_training.trainer import Trainer
from light_training.utils.files_helper import save_new_model_and_delete_last
from light_training.evaluation.metric import dice
import os
def func(m, epochs):
return np.exp(-10*(1- m / epochs)**2)
data_dir = "./data/fullres/train"
fold = 0
logdir = "./logs/diffunet"
env = "pytorch"
model_save_path = os.path.join(logdir, "model")
max_epoch = 1000
batch_size = 2
val_every = 2
num_gpus = 1
device = "cuda:0"
patch_size = [128, 128, 128]
# patch_size = [96, 96, 96]
augmentation = True
class BraTSTrainer(Trainer):
def __init__(self, env_type, max_epochs, batch_size, device="cpu", val_every=1, num_gpus=1, logdir="./logs/", master_ip='localhost', master_port=17750, training_script="train.py"):
super().__init__(env_type, max_epochs, batch_size, device, val_every, num_gpus, logdir, master_ip, master_port, training_script)
self.window_infer = SlidingWindowInferer(roi_size=patch_size,
sw_batch_size=2,
overlap=0.5)
self.patch_size = patch_size
self.augmentation = augmentation
self.train_process = 12
from diffunet.diffunet_model import DiffUNet
self.model = DiffUNet(4, 4)
self.best_mean_dice = 0.0
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=1e-2, weight_decay=3e-5,
momentum=0.99, nesterov=True)
self.scheduler_type = "poly"
self.loss_func = nn.CrossEntropyLoss()
def convert_labels(self, labels):
## TC, WT and ET
result = [(labels == 1) | (labels == 3), (labels == 1) | (labels == 3) | (labels == 2), labels == 3]
return torch.cat(result, dim=1).float()
def training_step(self, batch):
import time
image, label = self.get_input(batch)
pred, pred_edge, uncertainty = self.model(image, label)
uncertainty = torch.clamp(uncertainty, 0.0, 1.0)
loss = self.loss_func(pred, label)
loss_edge = self.loss_func(pred_edge, label)
scale = func(self.epoch, max_epoch)
loss = loss.mean() + loss_edge.mean() + (loss * uncertainty).mean() * scale
self.log("training_loss", loss.mean(), step=self.global_step)
self.log("training_loss_edge", loss_edge.mean(), step=self.global_step)
return loss
# for image, label in data_loader:
def get_input(self, batch):
image = batch["data"]
label = batch["seg"]
# label = self.convert_labels(label)
label = label[:, 0].long()
return image, label
def cal_metric(self, gt, pred, voxel_spacing=[1.0, 1.0, 1.0]):
if pred.sum() > 0 and gt.sum() > 0:
d = dice(pred, gt)
# hd95 = metric.binary.hd95(pred, gt)
return np.array([d, 50])
elif gt.sum() == 0 and pred.sum() == 0:
return np.array([1.0, 50])
else:
return np.array([0.0, 50])
def validation_step(self, batch):
image, label = self.get_input(batch)
output = self.model(image, ddim=True)
output = output.argmax(dim=1)
output = output.cpu().numpy()
target = label.cpu().numpy()
dices = []
c = 4
for i in range(1, c):
pred_c = output == i
target_c = target == i
cal_dice, _ = self.cal_metric(target_c, pred_c)
dices.append(cal_dice)
return dices
def validation_end(self, val_outputs):
dices = val_outputs
dices_mean = []
c = 3
for i in range(0, c):
dices_mean.append(dices[i].mean())
mean_dice = sum(dices_mean) / len(dices_mean)
self.log("0", dices_mean[0], step=self.epoch)
self.log("1", dices_mean[1], step=self.epoch)
self.log("2", dices_mean[2], step=self.epoch)
self.log("mean_dice", mean_dice, step=self.epoch)
if mean_dice > self.best_mean_dice:
self.best_mean_dice = mean_dice
save_new_model_and_delete_last(self.model,
os.path.join(model_save_path,
f"best_model_{mean_dice:.4f}.pt"),
delete_symbol="best_model")
save_new_model_and_delete_last(self.model,
os.path.join(model_save_path,
f"final_model_{mean_dice:.4f}.pt"),
delete_symbol="final_model")
print(f"mean_dice is {mean_dice}")
if __name__ == "__main__":
trainer = BraTSTrainer(env_type=env,
max_epochs=max_epoch,
batch_size=batch_size,
device=device,
logdir=logdir,
val_every=val_every,
num_gpus=num_gpus,
master_port=17753,
training_script=__file__)
from test_list_brats2023 import test_list
train_ds, test_ds = get_train_test_loader_from_test_list(data_dir=data_dir, test_list=test_list)
trainer.train(train_dataset=train_ds, val_dataset=test_ds)