[8eeb5a]: / training / inductivenet_trainers.py

Download this file

361 lines (324 with data), 16.5 kB

  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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
354
355
356
357
358
359
360
import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.optim.optimizer
from torch.utils.data import DataLoader
from data.hyperkvasir import KvasirSegmentationDataset, KvasirMNVset
from evaluation.metrics import iou
from losses.consistency_losses import *
from perturbation.model import ModelOfNaturalVariation
from training.vanilla_trainer import VanillaTrainer
from utils import logging
from training.consistency_trainers import ConsistencyTrainer
from models.segmentation_models import InductiveNet
from models.ensembles import TrainedEnsemble
from data.hyperkvasir import KvasirSegmentationDataset, KvasirMNVset
from evaluation.metrics import iou
from losses.consistency_losses import *
from perturbation.model import ModelOfNaturalVariation
from training.vanilla_trainer import VanillaTrainer
from utils import logging
from data.etis import EtisDataset
class InductiveNetConsistencyTrainer:
def __init__(self, id, config):
"""
:param model: String describing the model type. Can be DeepLab, TriUnet, ... TODO
:param config: Contains hyperparameters : lr, epochs, batch_size, T_0, T_mult
"""
self.config = config
self.device = config["device"]
self.lr = config["lr"]
self.batch_size = config["batch_size"]
self.epochs = config["epochs"]
self.id = id
self.model_str = "InductiveNet"
self.mnv = ModelOfNaturalVariation(T0=1).to(self.device)
self.nakedcloss = NakedConsistencyLoss()
self.closs = ConsistencyLoss()
self.model = InductiveNet().to(self.device)
self.optimizer = torch.optim.Adam(self.model.parameters(), self.lr)
self.jaccard = vanilla_losses.JaccardLoss()
self.mse = nn.MSELoss()
self.scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(self.optimizer, T_0=50, T_mult=2)
self.train_set = KvasirSegmentationDataset("Datasets/HyperKvasir", split="train", augment=False)
self.val_set = KvasirSegmentationDataset("Datasets/HyperKvasir", split="val")
self.test_set = KvasirSegmentationDataset("Datasets/HyperKvasir", split="test")
self.train_loader = DataLoader(self.train_set, batch_size=self.batch_size, shuffle=True)
self.val_loader = DataLoader(self.val_set)
self.test_loader = DataLoader(self.test_set)
def train_epoch(self):
self.model.train()
losses = []
for x, y, fname in self.train_loader:
image = x.to("cuda")
mask = y.to("cuda")
aug_img, aug_mask = self.mnv(image, mask)
self.optimizer.zero_grad()
aug_output, _ = self.model(aug_img)
output, reconstruction = self.model(image)
mean_iou = torch.mean(iou(output, mask))
loss = 0.5 * (self.closs(aug_mask, mask, aug_output, output, mean_iou) + self.mse(
image, reconstruction))
loss.backward()
self.optimizer.step()
losses.append(np.abs(loss.item()))
return np.mean(losses)
def train(self):
best_val_loss = 10
print("Starting Segmentation training")
best_consistency = 0
for i in range(self.epochs):
training_loss = np.abs(self.train_epoch())
val_loss, ious, closs = self.validate(epoch=i, plot=False)
gen_ious = self.validate_generalizability(epoch=i, plot=False)
mean_iou = float(torch.mean(ious))
gen_iou = float(torch.mean(gen_ious))
consistency = 1 - np.mean(closs)
test_iou = np.mean(self.test().numpy())
self.config["lr"] = [group['lr'] for group in self.optimizer.param_groups]
logging.log_full(epoch=i, id=self.id, config=self.config, result_dict=
{"train_loss": training_loss, "val_loss": val_loss,
"iid_val_iou": mean_iou, "iid_test_iou": test_iou, "ood_iou": gen_iou,
"consistency": consistency}, type="consistency")
self.scheduler.step(i)
print(
f"Epoch {i} of {self.epochs} \t"
f" lr={[group['lr'] for group in self.optimizer.param_groups]} \t"
f" loss={training_loss} \t"
f" val_loss={val_loss} \t"
f" ood_iou={gen_iou}\t"
f" val_iou={mean_iou} \t"
f" gen_prop={gen_iou / mean_iou}"
)
if val_loss < best_val_loss:
best_val_loss = val_loss
np.save(
f"experiments/Data/Augmented-Pipelines/{self.model_str}/{self.id}",
test_iou)
print(f"Saving new best model. IID test-set mean iou: {test_iou}")
torch.save(self.model.state_dict(),
f"Predictors/Augmented/{self.model_str}/{self.id}")
print("saved in: ", f"Predictors/Augmented/{self.model_str}/{self.id}")
if consistency > best_consistency:
best_consistency = consistency
torch.save(self.model.state_dict(),
f"Predictors/Augmented/{self.model_str}/maximum_consistency{self.id}")
torch.save(self.model.state_dict(),
f"Predictors/Augmented/{self.model_str}/{self.id}_last_epoch")
def test(self):
self.model.eval()
ious = torch.empty((0,))
with torch.no_grad():
for x, y, fname in self.test_loader:
image = x.to("cuda")
mask = y.to("cuda")
output, _ = self.model(image)
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
ious = torch.cat((ious, batch_ious.flatten()))
return ious
def validate(self, epoch, plot=False):
self.model.eval()
losses = []
closses = []
ious = torch.empty((0,))
with torch.no_grad():
for x, y, fname in self.val_loader:
image = x.to("cuda")
mask = y.to("cuda")
aug_img, aug_mask = self.mnv(image, mask)
output, reconstruction = self.model(image)
aug_output, _ = self.model(aug_img) # todo consider train on augmented vs non-augmented?
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
loss = 0.5 * (self.closs(aug_mask, mask, aug_output, output, torch.mean(batch_ious)) + self.mse(
image, reconstruction))
losses.append(np.abs(loss.item()))
closses.append(self.nakedcloss(aug_mask, mask, aug_output, output).item())
ious = torch.cat((ious, batch_ious.cpu().flatten()))
if plot:
plt.imshow(output[0, 0].cpu().numpy(), alpha=0.5)
plt.imshow(reconstruction[0].permute(1, 2, 0).cpu().numpy())
# plt.imshow((output[0, 0].cpu().numpy() > 0.5).astype(int), alpha=0.5)
# plt.imshow(y[0, 0].cpu().numpy().astype(int), alpha=0.5)
# plt.title("IoU {} at epoch {}".format(iou(output[0, 0], mask[0, 0]), epoch))
plt.show()
plot = False # plot one example per epoch
avg_val_loss = np.mean(losses)
avg_closs = np.mean(closses)
return avg_val_loss, ious, closses
def validate_generalizability(self, epoch, plot=False):
self.model.eval()
ious = torch.empty((0,))
with torch.no_grad():
for x, y, index in DataLoader(EtisDataset("Datasets/ETIS-LaribPolypDB")):
image = x.to("cuda")
mask = y.to("cuda")
output, _ = self.model(image)
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
ious = torch.cat((ious, batch_ious.flatten()))
if plot:
plt.imshow(image[0].permute(1, 2, 0).cpu().numpy())
plt.imshow((output[0, 0].cpu().numpy() > 0.5).astype(int), alpha=0.5)
plt.title("IoU {} at epoch {}".format(iou(output[0, 0], mask[0, 0]), epoch))
plt.show()
plot = False # plot one example per epoch (hacky, but works)
return ious
class InductiveNetVanillaTrainer(InductiveNetConsistencyTrainer):
def __init__(self, id, config):
super(InductiveNetVanillaTrainer, self).__init__(id, config)
def train(self):
best_val_loss = 10
print("Starting Segmentation training")
best_consistency = 0
for i in range(self.epochs):
training_loss = np.abs(self.train_epoch())
val_loss, ious, closs = self.validate(epoch=i, plot=False)
gen_ious = self.validate_generalizability(epoch=i, plot=False)
mean_iou = float(torch.mean(ious))
gen_iou = float(torch.mean(gen_ious))
consistency = 1 - np.mean(closs)
test_iou = np.mean(self.test().numpy())
self.config["lr"] = [group['lr'] for group in self.optimizer.param_groups]
logging.log_full(epoch=i, id=self.id, config=self.config, result_dict=
{"train_loss": training_loss, "val_loss": val_loss,
"iid_val_iou": mean_iou, "iid_test_iou": test_iou, "ood_iou": gen_iou,
"consistency": consistency}, type="consistency")
self.scheduler.step(i)
print(
f"Epoch {i} of {self.epochs} \t"
f" lr={[group['lr'] for group in self.optimizer.param_groups]} \t"
f" loss={training_loss} \t"
f" val_loss={val_loss} \t"
f" ood_iou={gen_iou}\t"
f" val_iou={mean_iou} \t"
f" gen_prop={gen_iou / mean_iou}"
)
if val_loss < best_val_loss:
best_val_loss = val_loss
np.save(
f"experiments/Data/Normal-Pipelines/{self.model_str}/{self.id}",
test_iou)
print(f"Saving new best model. IID test-set mean iou: {test_iou}")
torch.save(self.model.state_dict(),
f"Predictors/Vanilla/{self.model_str}/{self.id}")
print("saved in: ", f"Predictors/Vanilla/{self.model_str}/{self.id}")
if consistency > best_consistency:
best_consistency = consistency
torch.save(self.model.state_dict(),
f"Predictors/Vanilla/{self.model_str}/maximum_consistency{self.id}")
torch.save(self.model.state_dict(),
f"Predictors/Vanilla/{self.model_str}/{self.id}_last_epoch")
def train_epoch(self):
self.model.train()
losses = []
for x, y, fname in self.train_loader:
image = x.to("cuda")
mask = y.to("cuda")
self.optimizer.zero_grad()
output, reconstruction = self.model(image)
mean_iou = torch.mean(iou(output, mask))
loss = 0.5 * (self.jaccard(output, mask) + self.mse(
image, reconstruction))
loss.backward()
self.optimizer.step()
losses.append(np.abs(loss.item()))
return np.mean(losses)
def test(self):
self.model.eval()
ious = torch.empty((0,))
with torch.no_grad():
for x, y, fname in self.test_loader:
image = x.to("cuda")
mask = y.to("cuda")
output = self.model(image)
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
ious = torch.cat((ious, batch_ious.flatten()))
return ious
def validate(self, epoch, plot=False):
self.model.eval()
losses = []
closses = []
ious = torch.empty((0,))
with torch.no_grad():
for x, y, fname in self.val_loader:
image = x.to("cuda")
mask = y.to("cuda")
aug_img, aug_mask = self.mnv(image, mask)
output, reconstruction = self.model(image)
aug_output, _ = self.model(aug_img) # todo consider train on augmented vs non-augmented?
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
loss = 0.5 * (self.jaccard(output, mask) + self.mse(
image, reconstruction))
losses.append(np.abs(loss.item()))
closses.append(self.nakedcloss(aug_mask, mask, aug_output, output).item())
ious = torch.cat((ious, batch_ious.cpu().flatten()))
if plot:
plt.imshow(output[0, 0].cpu().numpy(), alpha=0.5)
plt.imshow(reconstruction[0].permute(1, 2, 0).cpu().numpy())
# plt.imshow((output[0, 0].cpu().numpy() > 0.5).astype(int), alpha=0.5)
# plt.imshow(y[0, 0].cpu().numpy().astype(int), alpha=0.5)
# plt.title("IoU {} at epoch {}".format(iou(output[0, 0], mask[0, 0]), epoch))
plt.show()
plot = False # plot one example per epoch
avg_val_loss = np.mean(losses)
avg_closs = np.mean(closses)
return avg_val_loss, ious, avg_closs
def validate_generalizability(self, epoch, plot=False):
self.model.eval()
ious = torch.empty((0,))
with torch.no_grad():
for x, y, index in DataLoader(EtisDataset("Datasets/ETIS-LaribPolypDB")):
image = x.to("cuda")
mask = y.to("cuda")
output, _ = self.model(image)
batch_ious = torch.Tensor([iou(output_i, mask_j) for output_i, mask_j in zip(output, mask)])
ious = torch.cat((ious, batch_ious.flatten()))
if plot:
plt.imshow(image[0].permute(1, 2, 0).cpu().numpy())
plt.imshow((output[0, 0].cpu().numpy() > 0.5).astype(int), alpha=0.5)
plt.title("IoU {} at epoch {}".format(iou(output[0, 0], mask[0, 0]), epoch))
plt.show()
plot = False # plot one example per epoch (hacky, but works)
return ious
class InductiveNetAugmentationTrainer(InductiveNetConsistencyTrainer):
"""
Uses vanilla data augmentation with p=0.5 instead of a a custom loss
"""
def __init__(self, id, config):
super(InductiveNetAugmentationTrainer, self).__init__(id, config)
self.jaccard = vanilla_losses.JaccardLoss()
self.mse = vanilla_losses.MSELoss()
self.prob = 0
self.dataset = KvasirMNVset("Datasets/HyperKvasir", "train", inpaint=config["use_inpainter"])
self.train_loader = DataLoader(self.dataset, batch_size=config["batch_size"], shuffle=True)
def get_iou_weights(self, image, mask):
self.model.eval()
with torch.no_grad():
output, _ = self.model(image)
return torch.mean(iou(output, mask))
def get_consistency(self, image, mask, augmented, augmask):
self.model.eval()
with torch.no_grad():
output, _ = self.model(image)
self.model.train()
return torch.mean(self.nakedcloss(output, mask, augmented, augmask))
def train_epoch(self):
self.model.train()
losses = []
for x, y, fname, flag in self.train_loader:
image = x.to("cuda")
mask = y.to("cuda")
self.optimizer.zero_grad()
output, reconstruction = self.model(image)
mean_iou = torch.mean(iou(output, mask))
loss = 0.5 * (self.jaccard(output, mask) + self.mse(
image, reconstruction))
loss.backward()
self.optimizer.step()
losses.append(np.abs(loss.item()))
return np.mean(losses)
class InductiveNetEnsembleTrainer(InductiveNetConsistencyTrainer):
def __init__(self, id, config):
super(InductiveNetEnsembleTrainer, self).__init__(id, config)
self.model = TrainedEnsemble("Singular")
self.optimizer = torch.optim.Adam(self.model.parameters(), self.lr)
self.scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(self.optimizer, T_0=50, T_mult=2)