-
Notifications
You must be signed in to change notification settings - Fork 1
/
reconstructor.py
217 lines (187 loc) · 8.84 KB
/
reconstructor.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import torch.nn as nn
import torch
import os
import numpy as np
from utils import device
from utils import MSELoss, GDLoss
from utils import DC, HD
class Reconstructor(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
self.init_layers()
self.apply(self.weight_init)
self.optimizer = torch.optim.Adam(self.parameters(), lr=args.lr, weight_decay=1e-5)
def init_layers(self):
self.encoder = nn.Sequential(
nn.Conv2d(in_channels=self.args.in_channels, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=128),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.Conv2d(
in_channels=32,
out_channels=self.args.latent_size,
kernel_size=self.args.last_layer[0],
stride=self.args.last_layer[1],
padding=self.args.last_layer[2]
)
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(
in_channels=self.args.latent_size,
out_channels=32,
kernel_size=self.args.last_layer[0],
stride=self.args.last_layer[1],
padding=self.args.last_layer[2]
),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=128),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=64),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=64, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=4, stride=2, padding=1),
nn.BatchNorm2d(num_features=32),
nn.LeakyReLU(.2),
nn.Dropout(0.5),
nn.ConvTranspose2d(in_channels=32, out_channels=self.args.in_channels, kernel_size=4, stride=2, padding=1),
nn.Softmax(dim=1)
)
def weight_init(self, m):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
nn.init.kaiming_uniform_(m.weight)
def forward(self, x):
latent = self.encoder(x)
reconstruction = self.decoder(latent)
return reconstruction
def Loss(self, prediction, target, epoch=None, validation=False):
contributes = {}
contributes["MSELoss"] = MSELoss(prediction,target)
contributes["GDLoss"] = GDLoss(prediction,target)
contributes["Total"] = sum(contributes.values())
if validation:
return {k:v.item() for k,v in contributes.items()}
return contributes["Total"]
def Metrics(self,prediction,target):
metrics = {}
for c, key in enumerate(["LV_", "MYO_", "RV_"], start=1):
ref = np.copy(target)
pred = np.copy(prediction)
ref = np.where(ref != c, 0, 1)
pred = np.where(pred != c, 0, 1)
metrics[key + "dc"] = DC(pred, ref)
metrics[key + "hd"] = HD(pred, ref)
return metrics
def training_routine(self, epochs, train_loader, val_loader, ckpt_folder):
if not os.path.isdir(ckpt_folder):
os.makedirs(ckpt_folder)
history = []
best_acc = np.inf
for epoch in epochs:
self.train()
for batch in train_loader:
batch = batch["gt"].to(device)
self.optimizer.zero_grad()
reconstruction = self.forward(batch)
loss = self.Loss(reconstruction, batch, epoch)
loss.backward()
self.optimizer.step()
self.eval()
with torch.no_grad():
result = self.evaluation_routine(val_loader)
if result["Total"] < best_acc or epoch%10 == 0:
ckpt = os.path.join(ckpt_folder, "{:03d}.pth".format(epoch))
if result["Total"] < best_acc:
best_acc = result["Total"]
ckpt = ckpt.split(".pth")[0] + "_best.pth"
torch.save({"R": self.state_dict(), "R_optim": self.optimizer.state_dict()}, ckpt)
self.epoch_end(epoch, result)
history.append(result["Total"])
return history
def evaluation_routine(self, val_loader):
epoch_summary={}
for patient in val_loader:
gt, reconstruction = [], []
for batch in patient:
batch = {"gt": batch["gt"].to(device)}
batch["reconstruction"] = self.forward(batch["gt"])
gt = torch.cat([gt,batch["gt"]], dim=0) if len(gt)>0 else batch["gt"]
reconstruction = torch.cat([reconstruction, batch["reconstruction"]], dim=0) if len(reconstruction)>0 else batch["reconstruction"]
for k,v in self.Loss(batch["reconstruction"], batch["gt"], validation=True).items():
if k not in epoch_summary.keys():
epoch_summary[k] = []
epoch_summary[k].append(v)
gt = np.argmax(gt.cpu().numpy(), axis=1)
gt = {"ED": gt[:len(gt)//2], "ES": gt[len(gt)//2:]}
reconstruction = np.argmax(reconstruction.cpu().numpy(), axis=1)
reconstruction = {"ED": reconstruction[:len(reconstruction)//2], "ES": reconstruction[len(reconstruction)//2:]}
for phase in ["ED","ES"]:
for k,v in self.Metrics(reconstruction[phase],gt[phase]).items():
if k not in epoch_summary.keys(): epoch_summary[k]=[]
epoch_summary[k].append(v)
epoch_summary = {k:np.mean(v) for k,v in epoch_summary.items()}
return epoch_summary
def epoch_end(self,epoch,result):
print("\033[1mEpoch [{}]\033[0m".format(epoch))
header, row = "", ""
for k,v in result.items():
header += "{:.6}\t".format(k)
row += "{:.6}\t".format("{:.4f}".format(v))
print(header);print(row)