2018-04-09 03:15:24 +00:00
|
|
|
import torch
|
2019-10-30 18:54:57 +00:00
|
|
|
import torch.nn.functional as F
|
2019-10-24 19:37:21 +00:00
|
|
|
from tqdm import tqdm
|
2017-11-30 06:44:34 +00:00
|
|
|
|
2018-06-08 17:27:32 +00:00
|
|
|
from dice_loss import dice_coeff
|
2017-08-19 08:59:51 +00:00
|
|
|
|
|
|
|
|
2020-03-11 08:06:23 +00:00
|
|
|
def eval_net(net, loader, device):
|
2018-06-08 17:27:32 +00:00
|
|
|
"""Evaluation without the densecrf with the dice coefficient"""
|
2018-09-26 06:57:10 +00:00
|
|
|
net.eval()
|
2020-03-11 08:06:23 +00:00
|
|
|
mask_type = torch.float32 if net.n_classes == 1 else torch.long
|
|
|
|
n_val = len(loader) # the number of batch
|
2017-08-19 08:59:51 +00:00
|
|
|
tot = 0
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2020-03-11 08:06:23 +00:00
|
|
|
with tqdm(total=n_val, desc='Validation round', unit='batch', leave=False) as pbar:
|
2019-11-23 16:56:14 +00:00
|
|
|
for batch in loader:
|
2020-03-11 08:06:23 +00:00
|
|
|
imgs, true_masks = batch['image'], batch['mask']
|
2019-11-23 16:56:14 +00:00
|
|
|
imgs = imgs.to(device=device, dtype=torch.float32)
|
2019-12-13 16:36:12 +00:00
|
|
|
true_masks = true_masks.to(device=device, dtype=mask_type)
|
2019-11-23 16:56:14 +00:00
|
|
|
|
2020-03-11 08:06:23 +00:00
|
|
|
with torch.no_grad():
|
|
|
|
mask_pred = net(imgs)
|
2019-11-23 16:56:14 +00:00
|
|
|
|
2020-03-11 08:06:23 +00:00
|
|
|
if net.n_classes > 1:
|
|
|
|
tot += F.cross_entropy(mask_pred, true_masks).item()
|
|
|
|
else:
|
|
|
|
pred = torch.sigmoid(mask_pred)
|
2019-12-02 11:06:29 +00:00
|
|
|
pred = (pred > 0.5).float()
|
2020-03-11 08:06:23 +00:00
|
|
|
tot += dice_coeff(pred, true_masks).item()
|
|
|
|
pbar.update()
|
2019-10-30 18:54:57 +00:00
|
|
|
|
2020-05-05 16:15:07 +00:00
|
|
|
net.train()
|
2019-10-24 19:37:21 +00:00
|
|
|
return tot / n_val
|