Пример #1
0
def runInference(args: argparse.Namespace):
    print('>>> Loading model')
    net = torch.load(args.model_weights)
    device = torch.device("cuda")
    net.to(device)

    print('>>> Loading the data')
    batch_size: int = args.batch_size
    num_classes: int = args.num_classes

    transform = transforms.Compose([
        lambda img: np.array(img)[np.newaxis, ...],
        lambda nd: nd / 255,  # max <= 1
        lambda nd: torch.tensor(nd, dtype=torch.float32)
    ])

    folders: List[Path] = [Path(args.data_folder)]
    names: List[str] = map_(lambda p: str(p.name), folders[0].glob("*.png"))
    dt_set = SliceDataset(names,
                          folders,
                          transforms=[transform],
                          debug=False,
                          C=num_classes)
    loader = DataLoader(dt_set,
                        batch_size=batch_size,
                        num_workers=batch_size + 2,
                        shuffle=False,
                        drop_last=False)

    print('>>> Starting the inference')
    savedir: str = args.save_folder
    total_iteration = len(loader)
    desc = f">> Inference"
    tq_iter = tqdm_(enumerate(loader), total=total_iteration, desc=desc)
    with torch.no_grad():
        for j, (filenames, image, _) in tq_iter:
            image = image.to(device)

            pred_logits: Tensor = net(image)
            pred_probs: Tensor = F.softmax(pred_logits, dim=1)

            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                predicted_class: Tensor = probs2class(pred_probs)
                save_images(predicted_class, filenames, savedir, "", 0)
Пример #2
0
def runInference(args: argparse.Namespace):
    print('>>> Loading model')
    net = torch.load(args.model_weights)
    device = torch.device("cuda")
    net.to(device)

    print('>>> Loading the data')
    batch_size: int = args.batch_size
    num_classes: int = args.num_classes

    folders: list[Path] = [Path(args.data_folder)]
    names: list[str] = map_(lambda p: str(p.name), folders[0].glob("*.png"))
    dt_set = SliceDataset(
        names,
        folders * 2,  # Duplicate for compatibility reasons
        are_hots=[False, False],
        transforms=[png_transform, dummy_gt_transform
                    ],  # So it is happy about the target size
        bounds_generators=[],
        debug=args.debug,
        K=num_classes)
    loader = DataLoader(dt_set,
                        batch_size=batch_size,
                        num_workers=batch_size + 2,
                        shuffle=False,
                        drop_last=False,
                        collate_fn=custom_collate)

    print('>>> Starting the inference')
    savedir: Path = Path(args.save_folder)
    savedir.mkdir(parents=True, exist_ok=True)
    total_iteration = len(loader)
    desc = ">> Inference"
    tq_iter = tqdm_(enumerate(loader), total=total_iteration, desc=desc)
    with torch.no_grad():
        for j, data in tq_iter:
            filenames: list[str] = data["filenames"]
            image: Tensor = data["images"].to(device)

            pred_logits: Tensor = net(image)
            pred_probs: Tensor = F.softmax(pred_logits, dim=1)

            with warnings.catch_warnings():
                warnings.simplefilter("ignore")

                predicted_class: Tensor
                if args.mode == 'argmax':
                    predicted_class = probs2class(pred_probs)
                elif args.mode == 'probs':
                    predicted_class = (pred_probs[:, args.probs_class, ...] *
                                       255).type(torch.uint8)
                elif args.mode == 'threshold':
                    thresholded: Tensor = pred_probs[:, ...] > args.threshold
                    predicted_class = thresholded.argmax(dim=1)
                elif args.mode == 'softmax':
                    for i, filename in enumerate(filenames):
                        np.save((savedir / filename).with_suffix(".npy"),
                                pred_probs[i].cpu().numpy())

                if args.mode != 'softmax':
                    save_images(predicted_class, filenames, savedir)
Пример #3
0
def do_epoch(args, mode: str, net: Any, device: Any, loader: DataLoader, epc: int,
             loss_fns: List[Callable], loss_weights: List[float],loss_fns_source: List[Callable],
             loss_weights_source: List[float], new_w:int, num_steps:int, C: int, metric_axis:List[int], savedir: str = "",
             optimizer: Any = None, target_loader: Any = None):

    assert mode in ["train", "val"]
    L: int = len(loss_fns)
    indices = torch.tensor(metric_axis,device=device)
    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        # net.train()
        desc = f">> Validation ({epc})"

    total_it_s, total_images = len(loader), len(loader.dataset)
    total_it_t, total_images_t = len(target_loader), len(target_loader.dataset)
    total_iteration = max(total_it_s, total_it_t)
    # Lazy add lines below because we will be cycling until the biggest length is reached
    total_images = max(total_images, total_images_t)
    total_images_t = total_images

    pho=1
    dtype = eval(args.dtype)

    all_dices: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_inter_card: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_card_gt: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_card_pred: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    loss_log: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_inf: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_cons: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_fs: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    posim_log: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    haussdorf_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_grp: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    dice_3d_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    dice_3d_sd_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)

    if args.source_metrics == True:
    	all_dices_s: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	all_inter_card_s: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	all_card_gt_s: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	all_card_pred_s: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	all_grp_s: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	dice_3d_s_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    	dice_3d_s_sd_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    # if len(loader)>len(target_loader):
    #     tq_iter = tqdm_(enumerate(zip(loader, cycle(target_loader))), total=total_iteration, desc=desc)
    # elif len(loader)<len(target_loader):
    #     tq_iter = tqdm_(enumerate(zip(cycle(loader), target_loader)), total=total_iteration, desc=desc)
    # else:
    #     tq_iter = tqdm_(enumerate(zip(loader, target_loader)), total=total_iteration, desc=desc)
    tq_iter = tqdm_(enumerate(zip(loader, target_loader)), total=total_iteration, desc=desc)
    #tq_iter = tqdm_(enumerate(target_loader), total=total_iteration, desc=desc)
    done: int = 0
    #ratio_losses = 0
    n_warmup = 0
    mult_lw = [pho ** (epc - n_warmup + 1)] * len(loss_weights)
    #if epc > 100:
    #    mult_lw = [pho ** 100] * len(loss_weights)
    mult_lw[0] = 1
    loss_weights = [a * b for a, b in zip(loss_weights, mult_lw)]
    losses_vec, source_vec, target_vec, baseline_target_vec = [], [], [], []
    pen_count = 0
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        for j, (source_data, target_data) in tq_iter:
        #for j, target_data in tq_iter:
            source_data[1:] = [e.to(device) for e in source_data[1:]]  # Move all tensors to device
            filenames_source, source_image, source_gt = source_data[:3]
            target_data[1:] = [e.to(device) for e in target_data[1:]]  # Move all tensors to device
            filenames_target, target_image, target_gt = target_data[:3]
            labels = target_data[3:3+L]
            labels_source = source_data[3:3 + L]
            bounds = target_data[3+L:]
            bounds_source = source_data[3+L:]
            
            assert len(labels) == len(bounds), len(bounds)
            if args.mix == False:
            	assert filenames_source == filenames_target
            #print(filenames_source,filenames_target)
            B = len(target_image)
            # Reset gradients
            if optimizer:
                #adjust_learning_rate(optimizer, 1, args.l_rate, num_steps, args.power)
                optimizer.zero_grad()

            # Forward
            with torch.set_grad_enabled(mode == "train"):
                pred_logits: Tensor = net(target_image)
                pred_logits_source: Tensor = net(source_image)
                pred_probs: Tensor = F.softmax(pred_logits, dim=1)
                pred_probs_source: Tensor = F.softmax(pred_logits_source, dim=1)
                if new_w > 0:
                    pred_probs = resize(pred_probs, new_w)
                    labels = [resize(label, new_w) for label in labels]
                    target = resize(target, new_w)
                predicted_mask: Tensor = probs2one_hot(pred_probs)  # Used only for dice computation
                predicted_mask_source: Tensor = probs2one_hot(pred_probs_source)  # Used only for dice computation
                #print(torch.sum(predicted_mask, dim=[2,3]).cpu().numpy())     
                #print(list(map(lambda n: [int(f) for f in n], np.around(torch.sum(pred_probs, dim=[2,3]).detach().cpu().numpy()))))     
            assert len(bounds) == len(loss_fns) == len(loss_weights)
            if epc < n_warmup:
                loss_weights = [0]*len(loss_weights)
            loss: Tensor = torch.zeros(1, requires_grad=True).to(device)
            loss_vec = []
            loss_k = []
            for loss_fn,label, w, bound in zip(loss_fns,labels, loss_weights, bounds):
                if w > 0:
                    if args.lin_aug_w:
                        if epc<70:
                            w=w*(epc+1)/70
                    loss_b =  loss_fn(pred_probs, label, bound)
                    loss = loss + w * loss_b
                    #pen_count += count_b.detach()
                    #print(count_b.detach())
                    loss_k.append(w*loss_b.detach())
            #for loss_fn, label, w, bound in zip(loss_fns_source, [source_gt], loss_weights_source, torch.randn(1)):
            #for loss_fn, label, w, bound in zip(loss_fns_source, labels_source, loss_weights_source, torch.randn(1)):
            for loss_fn, label, w, bound in zip(loss_fns_source, labels_source, loss_weights_source, bounds_source):
                if w > 0:
                    loss_b =  loss_fn(pred_probs_source, label, bound)
                    loss = loss+ w * loss_b
                    loss_k.append(w*loss_b.detach())
            #print(loss_k)
            # Backward
            if optimizer:
                loss.backward()
                optimizer.step()

            # Compute and log metrics
            #dices: Tensor = dice_coef(predicted_mask.detach(), target.detach())
            # baseline_dices: Tensor = dice_coef(labels[0].detach(), target.detach())
            #batch_dice: Tensor = dice_batch(predicted_mask.detach(), target.detach())
            # assert batch_dice.shape == (C,) and dices.shape == (B, C), (batch_dice.shape, dices.shape, B, C)
            dices, inter_card, card_gt, card_pred = dice_coef(predicted_mask.detach(), target_gt.detach())
            assert dices.shape == (B, C), (dices.shape, B, C)
            
            sm_slice = slice(done, done + B)  # Values only for current batch
            all_dices[sm_slice, ...] = dices
            # # for 3D dice
            all_grp[sm_slice, ...] = int(re.split('_', filenames_target[0])[1]) * torch.ones([1, C])
            all_inter_card[sm_slice, ...] = inter_card
            all_card_gt[sm_slice, ...] = card_gt
            all_card_pred[sm_slice, ...] = card_pred

            # 3D dice on source
            if args.source_metrics ==True:
            	dices_s, inter_card_s, card_gt_s, card_pred_s = dice_coef(predicted_mask_source.detach(), source_gt.detach())
            	all_grp_s[sm_slice, ...] = int(re.split('_', filenames_source[0])[1]) * torch.ones([1, C])
            	all_inter_card_s[sm_slice, ...] = inter_card_s
            	all_card_gt_s[sm_slice, ...] = card_gt_s
            	all_card_pred_s[sm_slice, ...] = card_pred_s

            #loss_log[sm_slice] = loss.detach()

            loss_inf[sm_slice] = loss_k[0]
            if len(loss_k)>1:
            	loss_cons[sm_slice] = loss_k[1]
            else:
            	loss_cons[sm_slice] = 0
            if len(loss_k)>2:
            	loss_fs[sm_slice] = loss_k[2]
            else:
            	loss_fs[sm_slice] = 0
            #posim_log[sm_slice] = torch.einsum("bcwh->b", [target_gt[:, 1:, :, :]]).detach() > 0
            
            #haussdorf_res: Tensor = haussdorf(predicted_mask.detach(), target_gt.detach(), dtype)
            #assert haussdorf_res.shape == (B, C)
            #haussdorf_log[sm_slice] = haussdorf_res
            
            # # Save images
            if savedir:
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=UserWarning)
                    warnings.simplefilter("ignore") 
                    predicted_class: Tensor = probs2class(pred_probs)
                    #save_images_p(predicted_class, filenames_target, args.dataset, mode, epc, False)
                    save_images(predicted_class, filenames_target, savedir, mode, epc, True)
          
            # Logging
            big_slice = slice(0, done + B)  # Value for current and previous batches
            stat_dict = {"dice": torch.index_select(all_dices, 1, indices).mean(),
                         "loss": loss_log[big_slice].mean()}
            nice_dict = {k: f"{v:.4f}" for (k, v) in stat_dict.items()}
            
            done += B
            tq_iter.set_postfix(nice_dict)
        print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))
    #dice_posim = torch.masked_select(all_dices[:, -1], posim_log.type(dtype=torch.uint8)).mean()
    # dice3D gives back the 3d dice mai on images
    # if not args.debug:
    #    dice_3d_log_o, dice_3d_sd_log_o = dice3d(args.workdir, f"iter{epc:03d}", mode, "Subj_\\d+_",args.dataset + mode + '/CT_GT', C)

    dice_3d_log, dice_3d_sd_log = dice3dn(all_grp, all_inter_card, all_card_gt, all_card_pred,metric_axis,True)
    if args.source_metrics ==True:
        dice_3d_s_log, dice_3d_s_sd_log = dice3dn(all_grp_s, all_inter_card_s, all_card_gt_s, all_card_pred_s,metric_axis,True)
    print("mean 3d_dice over all patients:",dice_3d_log)
    #source_vec = [ dice_3d_s, dice_3d_sd_s, haussdorf_log_s]
    dice_2d = torch.index_select(all_dices, 1, indices).mean().cpu().numpy()
    target_vec = [ dice_3d_log, dice_3d_sd_log, dice_2d]
    if args.source_metrics ==True:
        source_vec = [ dice_3d_s_log, dice_3d_s_sd_log]
    else:
        source_vec = [0,0]
    #losses_vec = [loss_log.mean().item()]
    losses_vec = [loss_inf.mean().item(),loss_cons.mean().item(),loss_fs.mean().item()]
    return losses_vec, target_vec,source_vec
def do_epoch(mode: str, net: Any, device: Any, loader: DataLoader, epc: int,
             loss_fns: List[Callable], loss_weights: List[float], C: int,
             savedir: str = "", optimizer: Any = None,
             metric_axis: List[int] = [1], compute_haussdorf: bool = False) \
        -> Tuple[Tensor, Tensor, Tensor, Tensor]:
    assert mode in ["train", "val"]
    L: int = len(loss_fns)

    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        desc = f">> Validation ({epc})"

    total_iteration, total_images = len(loader), len(loader.dataset)
    all_dices: Tensor = torch.zeros((total_images, C),
                                    dtype=torch.float32,
                                    device=device)
    batch_dices: Tensor = torch.zeros((total_iteration, C),
                                      dtype=torch.float32,
                                      device=device)
    loss_log: Tensor = torch.zeros((total_iteration),
                                   dtype=torch.float32,
                                   device=device)
    haussdorf_log: Tensor = torch.zeros((total_images, C),
                                        dtype=torch.float32,
                                        device=device)

    tq_iter = tqdm_(enumerate(loader), total=total_iteration, desc=desc)
    done: int = 0
    for j, data in tq_iter:
        data[1:] = [e.to(device)
                    for e in data[1:]]  # Move all tensors to device
        filenames, image, target = data[:3]
        labels = data[3:3 + L]
        bounds = data[3 + L:]
        assert len(labels) == len(bounds)

        B = len(image)

        # Reset gradients
        if optimizer:
            optimizer.zero_grad()

        # Forward
        pred_logits: Tensor = net(image)
        pred_probs: Tensor = F.softmax(pred_logits, dim=1)
        predicted_mask: Tensor = probs2one_hot(
            pred_probs.detach())  # Used only for dice computation

        assert len(bounds) == len(loss_fns) == len(loss_weights)
        ziped = zip(loss_fns, labels, loss_weights, bounds)
        losses = [
            w * loss_fn(pred_probs, label, bound)
            for loss_fn, label, w, bound in ziped
        ]
        loss = reduce(add, losses)
        assert loss.shape == (), loss.shape

        # Backward
        if optimizer:
            loss.backward()
            optimizer.step()

        # Compute and log metrics
        loss_log[j] = loss.detach()

        sm_slice = slice(done, done + B)  # Values only for current batch

        dices: Tensor = dice_coef(predicted_mask, target.detach())
        assert dices.shape == (B, C), (dices.shape, B, C)
        all_dices[sm_slice, ...] = dices

        if B > 1 and mode == "val":
            batch_dice: Tensor = dice_batch(predicted_mask, target.detach())
            assert batch_dice.shape == (C, ), (batch_dice.shape, B, C)
            batch_dices[j] = batch_dice

        if compute_haussdorf:
            haussdorf_res: Tensor = haussdorf(predicted_mask.detach(),
                                              target.detach())
            assert haussdorf_res.shape == (B, C)
            haussdorf_log[sm_slice] = haussdorf_res

        # Save images
        if savedir:
            with warnings.catch_warnings():
                warnings.filterwarnings("ignore", category=UserWarning)
                predicted_class: Tensor = probs2class(pred_probs)
                save_images(predicted_class, filenames, savedir, mode, epc)

        # Logging
        big_slice = slice(0,
                          done + B)  # Value for current and previous batches

        dsc_dict = {
            f"DSC{n}": all_dices[big_slice, n].mean()
            for n in metric_axis
        }
        hauss_dict = {
            f"HD{n}": haussdorf_log[big_slice, n].mean()
            for n in metric_axis
        } if compute_haussdorf else {}
        batch_dict = {
            f"bDSC{n}": batch_dices[:j, n].mean()
            for n in metric_axis
        } if B > 1 and mode == "val" else {}

        mean_dict = {
            "DSC": all_dices[big_slice, metric_axis].mean(),
            "HD": haussdorf_log[big_slice, metric_axis].mean()
        } if len(metric_axis) > 1 else {}

        stat_dict = {
            **dsc_dict,
            **hauss_dict,
            **mean_dict,
            **batch_dict, "loss": loss_log[:j].mean()
        }
        nice_dict = {k: f"{v:.3f}" for (k, v) in stat_dict.items()}

        tq_iter.set_postfix(nice_dict)
        done += B
    print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))

    return loss_log, all_dices, batch_dices, haussdorf_log
Пример #5
0
def do_epoch(mode: str, net: Any, device: Any, loaders: List[DataLoader], epc: int,
             list_loss_fns: List[List[Callable]], list_loss_weights: List[List[float]], C: int,
             savedir: str = "", optimizer: Any = None,
             metric_axis: List[int] = [1], compute_haussdorf: bool = False, compute_miou: bool = False,
             temperature: float = 1) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tuple[None, Tensor]]:
    assert mode in ["train", "val"]

    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        desc = f">> Validation ({epc})"

    total_iteration: int = sum(len(loader) for loader in loaders)  # U
    total_images: int = sum(len(loader.dataset) for loader in loaders)  # D
    n_loss: int = max(map(len, list_loss_fns))

    all_dices: Tensor = torch.zeros((total_images, C), dtype=torch.float32, device=device)
    batch_dices: Tensor = torch.zeros((total_iteration, C), dtype=torch.float32, device=device)
    loss_log: Tensor = torch.zeros((total_iteration, n_loss), dtype=torch.float32, device=device)
    haussdorf_log: Tensor = torch.zeros((total_images, C), dtype=torch.float32, device=device)
    iiou_log: Tensor = torch.zeros((total_images, C), dtype=torch.float32, device=device)
    intersections: Tensor = torch.zeros((total_images, C), dtype=torch.float32, device=device)
    unions: Tensor = torch.zeros((total_images, C), dtype=torch.float32, device=device)

    few_axis: bool = len(metric_axis) <= 3

    done_img: int = 0
    done_batch: int = 0
    tq_iter = tqdm_(total=total_iteration, desc=desc)
    for i, (loader, loss_fns, loss_weights) in enumerate(zip(loaders, list_loss_fns, list_loss_weights)):
        L: int = len(loss_fns)

        for data in loader:
            data[1:] = [e.to(device) for e in data[1:]]  # Move all tensors to device
            filenames, image, target = data[:3]
            assert not target.requires_grad
            labels = data[3:3 + L]
            bounds = data[3 + L:]
            assert len(labels) == len(bounds)

            B = len(image)

            # Reset gradients
            if optimizer:
                optimizer.zero_grad()

            # Forward
            pred_logits: Tensor = net(image)
            pred_probs: Tensor = F.softmax(temperature * pred_logits, dim=1)
            predicted_mask: Tensor = probs2one_hot(pred_probs.detach())  # Used only for dice computation
            assert not predicted_mask.requires_grad

            assert len(bounds) == len(loss_fns) == len(loss_weights) == len(labels)
            ziped = zip(loss_fns, labels, loss_weights, bounds)
            losses = [w * loss_fn(pred_probs, label, bound) for loss_fn, label, w, bound in ziped]
            loss = reduce(add, losses)
            assert loss.shape == (), loss.shape

            # if epc >= 1 and False:
            #     import matplotlib.pyplot as plt
            #     _, axes = plt.subplots(nrows=1, ncols=3)
            #     axes[0].imshow(image[0, 0].cpu().numpy(), cmap='gray')
            #     axes[0].contour(target[0, 1].cpu().numpy(), cmap='rainbow')

            #     pred_np = pred_probs[0, 1].detach().cpu().numpy()
            #     axes[1].imshow(pred_np)

            #     bins = np.linspace(0, 1, 50)
            #     axes[2].hist(pred_np.flatten(), bins)
            #     print(bounds)
            #     print(bounds[2].cpu().numpy())
            #     print(bounds[2][0, 1].cpu().numpy())
            #     print(pred_np.sum())
            #     plt.show()

            # Backward
            if optimizer:
                loss.backward()
                optimizer.step()

            # Compute and log metrics
            # loss_log[done_batch] = loss.detach()
            for j in range(len(loss_fns)):
                loss_log[done_batch, j] = losses[j].detach()

            sm_slice = slice(done_img, done_img + B)  # Values only for current batch

            dices: Tensor = dice_coef(predicted_mask, target)
            assert dices.shape == (B, C), (dices.shape, B, C)
            all_dices[sm_slice, ...] = dices

            if B > 1 and mode == "val":
                batch_dice: Tensor = dice_batch(predicted_mask, target)
                assert batch_dice.shape == (C,), (batch_dice.shape, B, C)
                batch_dices[done_batch] = batch_dice

            if compute_haussdorf:
                haussdorf_res: Tensor = haussdorf(predicted_mask, target)
                assert haussdorf_res.shape == (B, C)
                haussdorf_log[sm_slice] = haussdorf_res
            if compute_miou:
                IoUs: Tensor = iIoU(predicted_mask, target)
                assert IoUs.shape == (B, C), IoUs.shape
                iiou_log[sm_slice] = IoUs
                intersections[sm_slice] = inter_sum(predicted_mask, target)
                unions[sm_slice] = union_sum(predicted_mask, target)

            # Save images
            if savedir:
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=UserWarning)
                    predicted_class: Tensor = probs2class(pred_probs)
                    save_images(predicted_class, filenames, savedir, mode, epc)

            # Logging
            big_slice = slice(0, done_img + B)  # Value for current and previous batches

            dsc_dict = {f"DSC{n}": all_dices[big_slice, n].mean() for n in metric_axis} if few_axis else {}

            hauss_dict = {f"HD{n}": haussdorf_log[big_slice, n].mean() for n in metric_axis} \
                if compute_haussdorf and few_axis else {}

            batch_dict = {f"bDSC{n}": batch_dices[:done_batch, n].mean() for n in metric_axis} \
                if B > 1 and mode == "val" and few_axis else {}

            miou_dict = {f"iIoU": iiou_log[big_slice, metric_axis].mean(),
                         f"mIoU": (intersections.sum(dim=0) / (unions.sum(dim=0) + 1e-10)).mean()} \
                if compute_miou else {}

            if len(metric_axis) > 1:
                mean_dict = {"DSC": all_dices[big_slice, metric_axis].mean()}
                if compute_haussdorf:
                    mean_dict["HD"] = haussdorf_log[big_slice, metric_axis].mean()
            else:
                mean_dict = {}

            stat_dict = {**miou_dict, **dsc_dict, **hauss_dict, **mean_dict, **batch_dict,
                         "loss": loss_log[:done_batch].mean()}
            nice_dict = {k: f"{v:.3f}" for (k, v) in stat_dict.items()}

            done_img += B
            done_batch += 1
            tq_iter.set_postfix({**nice_dict, "loader": str(i)})
            tq_iter.update(1)
    tq_iter.close()
    print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))

    if compute_miou:
        mIoUs: Tensor = (intersections.sum(dim=0) / (unions.sum(dim=0) + 1e-10))
        assert mIoUs.shape == (C,), mIoUs.shape
    else:
        mIoUs = None

    if not few_axis and False:
        print(f"DSC: {[f'{all_dices[:, n].mean():.3f}' for n in metric_axis]}")
        print(f"iIoU: {[f'{iiou_log[:, n].mean():.3f}' for n in metric_axis]}")
        if mIoUs:
            print(f"mIoU: {[f'{mIoUs[n]:.3f}' for n in metric_axis]}")

    return loss_log, all_dices, batch_dices, haussdorf_log, mIoUs
Пример #6
0
def do_epoch(
        mode: str,
        net: Any,
        device: Any,
        loaders: list[DataLoader],
        epc: int,
        list_loss_fns: list[list[Callable]],
        list_loss_weights: list[list[float]],
        K: int,
        savedir: str = "",
        optimizer: Any = None,
        metric_axis: list[int] = [1],
        compute_3d_dice: bool = False,
        temperature: float = 1) -> Tuple[Tensor, Tensor, Optional[Tensor]]:
    assert mode in ["train", "val", "dual"]

    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        desc = f">> Validation ({epc})"

    total_iteration: int = sum(len(loader) for loader in loaders)  # U
    total_images: int = sum(len(loader.dataset) for loader in loaders)  # D
    n_loss: int = max(map(len, list_loss_fns))

    all_dices: Tensor = torch.zeros((total_images, K),
                                    dtype=torch.float32,
                                    device=device)
    loss_log: Tensor = torch.zeros((total_iteration, n_loss),
                                   dtype=torch.float32,
                                   device=device)

    three_d_dices: Optional[Tensor]
    if compute_3d_dice:
        three_d_dices = torch.zeros((total_iteration, K),
                                    dtype=torch.float32,
                                    device=device)
    else:
        three_d_dices = None

    done_img: int = 0
    done_batch: int = 0
    tq_iter = tqdm_(total=total_iteration, desc=desc)
    for i, (loader, loss_fns, loss_weights) in enumerate(
            zip(loaders, list_loss_fns, list_loss_weights)):
        for data in loader:
            # t0 = time()
            image: Tensor = data["images"].to(device)
            target: Tensor = data["gt"].to(device)
            filenames: list[str] = data["filenames"]
            assert not target.requires_grad
            labels: list[Tensor] = [e.to(device) for e in data["labels"]]
            B, C, *_ = image.shape

            # Reset gradients
            if optimizer:
                optimizer.zero_grad()

            # Forward
            pred_logits: Tensor = net(image)
            pred_probs: Tensor = F.softmax(temperature * pred_logits, dim=1)
            predicted_mask: Tensor = probs2one_hot(
                pred_probs.detach())  # Used only for dice computation
            assert not predicted_mask.requires_grad

            assert len(loss_fns) == len(loss_weights) == len(labels)
            ziped = zip(loss_fns, labels, loss_weights)
            losses = [
                w * loss_fn(pred_probs, label) for loss_fn, label, w in ziped
            ]
            loss = reduce(add, losses)
            assert loss.shape == (), loss.shape

            # Backward
            if optimizer:
                loss.backward()
                optimizer.step()

            # Compute and log metrics
            for j in range(len(loss_fns)):
                loss_log[done_batch, j] = losses[j].detach()

            sm_slice = slice(done_img,
                             done_img + B)  # Values only for current batch

            dices: Tensor = dice_coef(predicted_mask, target)
            assert dices.shape == (B, K), (dices.shape, B, K)
            all_dices[sm_slice, ...] = dices

            if compute_3d_dice:
                three_d_DSC: Tensor = dice_batch(predicted_mask, target)
                assert three_d_DSC.shape == (K, )

                three_d_dices[done_batch] = three_d_DSC  # type: ignore

            # Save images
            if savedir:
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=UserWarning)
                    predicted_class: Tensor = probs2class(pred_probs)
                    save_images(predicted_class, filenames, savedir, mode, epc)

            # Logging
            big_slice = slice(0, done_img +
                              B)  # Value for current and previous batches

            dsc_dict: dict = {f"DSC{n}": all_dices[big_slice, n].mean() for n in metric_axis} | \
                ({f"3d_DSC{n}": three_d_dices[:done_batch, n].mean() for n in metric_axis}
                 if three_d_dices is not None else {})

            loss_dict = {
                f"loss_{i}": loss_log[:done_batch].mean(dim=0)[i]
                for i in range(n_loss)
            }

            stat_dict = dsc_dict | loss_dict
            nice_dict = {k: f"{v:.3f}" for (k, v) in stat_dict.items()}

            done_img += B
            done_batch += 1
            tq_iter.set_postfix({**nice_dict, "loader": str(i)})
            tq_iter.update(1)
    tq_iter.close()

    print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))

    return (loss_log.detach().cpu(), all_dices.detach().cpu(),
            three_d_dices.detach().cpu()
            if three_d_dices is not None else None)
Пример #7
0
    def update_labels(self, net, device, axis: int = 2, savedir: str = "") -> None:
        print(f"> Updating {len(self)} labels...")
        assert self.train_mode

        # w_, h_ = self.img_size
        h_, w_ = self.img_size
        u_raw = RawArray(ctypes.c_float, self.batch_size * self.K * h_ * w_)
        u_np = np.frombuffer(u_raw, dtype=np.float32).reshape(self.batch_size, self.K, h_, w_)

        img_raw = RawArray(ctypes.c_char, self.batch_size * 3 * h_ * w_)
        img_np = np.frombuffer(img_raw, dtype=np.uint8).reshape(self.batch_size, h_, w_, 3)

        final_raw = RawArray(ctypes.c_float, self.batch_size * self.K * h_ * w_)
        final_np = np.frombuffer(final_raw, dtype=np.float32).reshape(self.batch_size, self.K, h_, w_)

        pool = Pool(self.batch_size, initializer=init_crf_vars, initargs=(u_raw, img_raw, final_raw))

        i = 0
        with torch.no_grad():
            for data in tqdm(self.loader):
                imgs: Tensor = data['images'].to(device)
                uint_images: Tensor = data['uint_images']
                orig_boxes: Tensor = data['orig_boxes']

                logits: Tensor = net(imgs)
                probs: Tensor = F.softmax(logits, dim=1)

                assert simplex(probs)

                final_probs = torch.zeros_like(probs)
                U: np.ndarray = (-probs.log()).cpu().numpy()
                assert U.dtype == np.float32
                # del probs

                B, K, W, H = U.shape
                u_np[:B, ...] = U[:B, ...]

                assert B <= self.batch_size
                assert K == self.K
                assert (W, H) == self.img_size, (W, H, self.img_size)
                assert uint_images.shape == (B, W, H, 3), (uint_images.shape, (B, W, H, 3))

                proc_fn: Callable = partial(crf_post_process, B=self.batch_size, W=W, H=H, K=K)

                uintimages: np.ndarray = uint_images.numpy()
                img_np[:B, ...] = uintimages[:B, ...]

                pool.map(proc_fn, range(B))

                final_probs = torch.tensor(final_np[:B, ...])
                assert simplex(final_probs)

                proposals: Tensor = probs2class(final_probs)
                assert proposals.shape == (B, W, H), proposals.shape
                assert orig_boxes.shape == (B, K, W, H), orig_boxes.shape
                # We do not want the proposals to overflow outside the box
                final_proposals: Tensor = einsum("bwh,bwh->bwh", orig_boxes[:, 1, :, :], proposals)

                # for b in range(B):
                #     im = imgs[b, 0].cpu().numpy()
                #     gt = data['gt'][b, 1].cpu().numpy()

                #     import matplotlib.pyplot as plt
                #     from mpl_toolkits.axes_grid1 import ImageGrid

                #     fig = plt.figure()
                #     fig.clear()

                #     grid = ImageGrid(fig, 211, nrows_ncols=(1, 5))

                #     grid[0].imshow(im, cmap="gray")
                #     grid[0].imshow(gt, cmap='jet', alpha=.5, vmax=1)

                #     grid[1].imshow(im, cmap="gray")
                #     grid[1].imshow(orig_boxes[b, 1].cpu().numpy(), cmap='jet', alpha=.5, vmax=1)

                #     grid[2].imshow(im, cmap="gray")
                #     grid[2].imshow(probs[b, 1].cpu().numpy(), cmap='jet', alpha=.5, vmax=1)

                #     grid[3].imshow(im, cmap="gray")
                #     grid[3].imshow(final_probs[b, 1], cmap='jet', alpha=.5, vmax=1)

                #     grid[4].imshow(im, cmap="gray")
                #     grid[4].imshow(final_proposals[b], cmap='jet', alpha=.5, vmax=1)
                #     plt.show()

                # And now the interesting part, replace live the stored images
                for b in range(B):
                    # for proposal in final_proposals:  # type: ignore
                    proposal = final_proposals[b]
                    assert proposal.shape == self.img_size

                    pil_img = Image.fromarray(proposal.cpu().numpy().astype('uint8'), mode='L')
                    buffer_ = io.BytesIO()
                    pil_img.save(buffer_, format='PNG')

                    if savedir:
                        pil_img.save(str(Path(savedir, data["filenames"][b]).with_suffix(".png")))

                    # print(buffer_)

                    self.files[axis][i] = buffer_
                    i += 1

        assert i == len(self)
Пример #8
0
def runInference(args: argparse.Namespace):
    print('>>> Loading model')
    net = torch.load(args.model_weights)
    device = torch.device("cuda")
    net.to(device)

    print('>>> Loading the data')
    batch_size: int = args.batch_size
    num_classes: int = args.num_classes

    png_transform = transforms.Compose([
        lambda img: img.convert('L'),
        lambda img: np.array(img)[np.newaxis, ...],
        lambda nd: nd / 255,  # max <= 1
        lambda nd: torch.tensor(nd, dtype=torch.float32)
    ])
    dummy_gt = transforms.Compose([
        lambda img: np.array(img), lambda nd: torch.zeros(
            (num_classes, *(nd.shape)), dtype=torch.int64)
    ])

    folders: List[Path] = [Path(args.data_folder)]
    names: List[str] = map_(lambda p: str(p.name), folders[0].glob("*.png"))
    dt_set = SliceDataset(
        names,
        folders * 2,  # Duplicate for compatibility reasons
        are_hots=[False, False],
        transforms=[png_transform,
                    dummy_gt],  # So it is happy about the target size
        bounds_generators=[],
        debug=False,
        C=num_classes)
    loader = DataLoader(dt_set,
                        batch_size=batch_size,
                        num_workers=batch_size + 2,
                        shuffle=False,
                        drop_last=False)

    print('>>> Starting the inference')
    savedir: str = args.save_folder
    total_iteration = len(loader)
    desc = f">> Inference"
    tq_iter = tqdm_(enumerate(loader), total=total_iteration, desc=desc)
    with torch.no_grad():
        for j, (filenames, image, _) in tq_iter:
            image = image.to(device)

            pred_logits: Tensor = net(image)
            pred_probs: Tensor = F.softmax(pred_logits, dim=1)

            with warnings.catch_warnings():
                warnings.simplefilter("ignore")

                predicted_class: Tensor
                if args.mode == "argmax":
                    predicted_class = probs2class(pred_probs)
                elif args.mode == 'probs':
                    predicted_class = (pred_probs[:, args.probs_class, ...] *
                                       255).type(torch.uint8)
                elif args.mode == "threshold":
                    thresholded: Tensor = pred_probs[:, ...] > args.threshold
                    predicted_class = thresholded.argmax(dim=1)

                save_images(predicted_class, filenames, savedir, "", 0)
Пример #9
0
def do_epoch(args, mode: str, net: Any, device: Any, epc: int,
             loss_fns: List[Callable], loss_weights: List[float],
              new_w:int, C: int, metric_axis:List[int], savedir: str = "",
             optimizer: Any = None, target_loader: Any = None, best_dice3d_val:Any=None):

    assert mode in ["train", "val"]
    L: int = len(loss_fns)
    indices = torch.tensor(metric_axis,device=device)
    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        # net.train()
        desc = f">> Validation ({epc})"

    total_it_t, total_images_t = len(target_loader), len(target_loader.dataset)
    total_iteration = total_it_t
    total_images = total_images_t

    if args.debug:
        total_iteration = 10
    pho=1
    dtype = eval(args.dtype)

    all_dices: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_sizes: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_sizes: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_gt_sizes: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_sizes2: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_inter_card: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_card_gt: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_card_pred: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_gt = []
    all_pred = []
    if args.do_hd: 
        all_gt: Tensor = torch.zeros((total_images, args.wh, args.wh), dtype=dtype)
        all_pred: Tensor = torch.zeros((total_images, args.wh, args.wh), dtype=dtype)
    loss_log: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_cons: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_se: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    loss_tot: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    posim_log: Tensor = torch.zeros((total_images), dtype=dtype, device=device)
    haussdorf_log: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_grp: Tensor = torch.zeros((total_images, C), dtype=dtype, device=device)
    all_pnames = np.zeros([total_images]).astype('U256') 
    #dice_3d_log: Tensor = torch.zeros((1, C), dtype=dtype, device=device)
    dice_3d_log, dice_3d_sd_log = 0, 0
    #dice_3d_sd_log: Tensor = torch.zeros((1, C), dtype=dtype, device=device)
    hd_3d_log, asd_3d_log, hd_3d_sd_log, asd_3d_sd_log= 0, 0, 0, 0
    tq_iter = tqdm_(enumerate(target_loader), total=total_iteration, desc=desc)
    done: int = 0
    n_warmup = args.n_warmup
    mult_lw = [pho ** (epc - n_warmup + 1)] * len(loss_weights)
    mult_lw[0] = 1
    loss_weights = [a * b for a, b in zip(loss_weights, mult_lw)]
    losses_vec, source_vec, target_vec, baseline_target_vec = [], [], [], []
    pen_count = 0
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        count_losses = 0
        for j, target_data in tq_iter:
            target_data[1:] = [e.to(device) for e in target_data[1:]]  # Move all tensors to device
            filenames_target, target_image, target_gt = target_data[:3]
            #print("target", filenames_target)
            labels = target_data[3:3+L]
            bounds = target_data[3+L:]
            filenames_target = [f.split('.nii')[0] for f in filenames_target]
            assert len(labels) == len(bounds), len(bounds)
            B = len(target_image)
            # Reset gradients
            if optimizer:
                optimizer.zero_grad()

            # Forward
            with torch.set_grad_enabled(mode == "train"):
                pred_logits: Tensor = net(target_image)
                pred_probs: Tensor = F.softmax(pred_logits, dim=1)
                if new_w > 0:
                    pred_probs = resize(pred_probs, new_w)
                    labels = [resize(label, new_w) for label in labels]
                    target = resize(target, new_w)
                predicted_mask: Tensor = probs2one_hot(pred_probs)  # Used only for dice computation
            assert len(bounds) == len(loss_fns) == len(loss_weights)
            if epc < n_warmup:
                loss_weights = [0]*len(loss_weights)
            loss: Tensor = torch.zeros(1, requires_grad=True).to(device)
            loss_vec = []
            loss_kw = []
            for loss_fn,label, w, bound in zip(loss_fns,labels, loss_weights, bounds):
                if w > 0:
                    if eval(args.target_losses)[0][0]=="EntKLProp": 
                        loss_1, loss_cons_prior,est_prop =  loss_fn(pred_probs, label, bound)
                        loss = loss_1 + loss_cons_prior 
                    else:
                        loss =  loss_fn(pred_probs, label, bound)
                        loss = w*loss
                        loss_1 = loss
                    loss_kw.append(loss_1.detach())
           # Backward
            if optimizer:
                loss.backward()
                optimizer.step()
            dices, inter_card, card_gt, card_pred = dice_coef(predicted_mask.detach(), target_gt.detach())
            assert dices.shape == (B, C), (dices.shape, B, C)
            sm_slice = slice(done, done + B)  # Values only for current batch
            all_dices[sm_slice, ...] = dices
            if eval(args.target_losses)[0][0] in ["EntKLProp"]:
                all_sizes[sm_slice, ...] = torch.round(est_prop.detach()*target_image.shape[2]*target_image.shape[3])
            all_sizes2[sm_slice, ...] = torch.sum(predicted_mask,dim=(2,3)) 
            all_gt_sizes[sm_slice, ...] = torch.sum(target_gt,dim=(2,3)) 
            all_grp[sm_slice, ...] = torch.FloatTensor(get_subj_nb(filenames_target)).unsqueeze(1).repeat(1,C)
            all_pnames[sm_slice] = filenames_target
            all_inter_card[sm_slice, ...] = inter_card
            all_card_gt[sm_slice, ...] = card_gt
            all_card_pred[sm_slice, ...] = card_pred
            if args.do_hd:
                all_pred[sm_slice, ...] = probs2class(predicted_mask[:,:,:,:]).cpu().detach()
                all_gt[sm_slice, ...] = probs2class(target_gt).detach()
            loss_se[sm_slice] = loss_kw[0]
            if len(loss_kw)>1:
            	loss_cons[sm_slice] = loss_kw[1]
            	loss_tot[sm_slice] = loss_kw[1]+loss_kw[0]
            else:
            	loss_cons[sm_slice] = 0
            	loss_tot[sm_slice] = loss_kw[0]
            # # Save images
            if savedir and args.saveim and mode =="val":
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=UserWarning)
                    warnings.simplefilter("ignore") 
                    predicted_class: Tensor = probs2class(pred_probs)
                    save_images(predicted_class, filenames_target, savedir, mode, epc, False)
                    if args.entmap:
                        ent_map = torch.einsum("bcwh,bcwh->bwh", [-pred_probs, (pred_probs+1e-10).log()])
                        save_images_ent(ent_map, filenames_target, savedir,'ent_map', epc)

            # Logging
            big_slice = slice(0, done + B)  # Value for current and previous batches
            stat_dict = {**{f"DSC{n}": all_dices[big_slice, n].mean() for n in metric_axis},
                         **{f"SZ{n}": all_sizes[big_slice, n].mean() for n in metric_axis},
                         **({f"DSC_source{n}": all_dices_s[big_slice, n].mean() for n in metric_axis}
                           if args.source_metrics else {})}

            size_dict = {**{f"SZ{n}": all_sizes[big_slice, n].mean() for n in metric_axis}}
            nice_dict = {k: f"{v:.4f}" for (k, v) in stat_dict.items()}
            done += B
            tq_iter.set_postfix(nice_dict)
    if args.dice_3d and (mode == 'val'):
        dice_3d_log, dice_3d_sd_log,asd_3d_log, asd_3d_sd_log,hd_3d_log, hd_3d_sd_log = dice3d(all_grp, all_inter_card, all_card_gt, all_card_pred,all_pred,all_gt,all_pnames,metric_axis,args.pprint,args.do_hd,args.do_asd,best_dice3d_val)
    dice_2d = torch.index_select(all_dices, 1, indices).mean().cpu().numpy().item()
    target_vec = [dice_3d_log, dice_3d_sd_log,asd_3d_log, asd_3d_sd_log,hd_3d_log,hd_3d_sd_log,dice_2d]
    size_mean = torch.index_select(all_sizes2, 1, indices).mean(dim=0).cpu().numpy()
    size_gt_mean = torch.index_select(all_gt_sizes, 1, indices).mean(dim=0).cpu().numpy()
    mask_pos = torch.index_select(all_sizes2, 1, indices)!=0
    gt_pos = torch.index_select(all_gt_sizes, 1, indices)!=0
    size_mean_pos = torch.index_select(all_sizes2, 1, indices).sum(dim=0).cpu().numpy()/mask_pos.sum(dim=0).cpu().numpy()
    gt_size_mean_pos = torch.index_select(all_gt_sizes, 1, indices).sum(dim=0).cpu().numpy()/gt_pos.sum(dim=0).cpu().numpy()
    size_mean2 = torch.index_select(all_sizes2, 1, indices).mean(dim=0).cpu().numpy()
    losses_vec = [loss_se.mean().item(),loss_cons.mean().item(),loss_tot.mean().item(),size_mean.mean(),size_mean_pos.mean(),size_gt_mean.mean(),gt_size_mean_pos.mean()]
    if not epc%50:
        df_t = pd.DataFrame({
           "val_ids":all_pnames,
           "proposal_size":all_sizes2.cpu()})
        df_t.to_csv(Path(savedir,mode+str(epc)+"sizes.csv"), float_format="%.4f", index_label="epoch")
    return losses_vec, target_vec,source_vec
Пример #10
0
def do_save_images(pred_probs, savedir, filenames, mode, epc):
    if savedir:
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=UserWarning)
            predicted_class: Tensor = probs2class(pred_probs)
            save_images(predicted_class, filenames, savedir, mode, epc, True)
Пример #11
0
def do_epoch(
    mode: str,
    net: Any,
    device: Any,
    loaders: List[DataLoader],
    epc: int,
    list_loss_fns: List[List[Callable]],
    list_loss_weights: List[List[float]],
    K: int,
    savedir: str = "",
    optimizer: Any = None,
    metric_axis: List[int] = [1],
    compute_hausdorff: bool = False,
    compute_miou: bool = False,
    compute_3d_dice: bool = False,
    temperature: float = 1
) -> Tuple[Tensor, Tensor, Optional[Tensor], Optional[Tensor],
           Optional[Tensor]]:
    assert mode in ["train", "val"]

    if mode == "train":
        net.train()
        desc = f">> Training   ({epc})"
    elif mode == "val":
        net.eval()
        desc = f">> Validation ({epc})"

    total_iteration: int = sum(len(loader) for loader in loaders)  # U
    total_images: int = sum(len(loader.dataset) for loader in loaders)  # D
    n_loss: int = max(map(len, list_loss_fns))

    all_dices: Tensor = torch.zeros((total_images, K),
                                    dtype=torch.float32,
                                    device=device)
    loss_log: Tensor = torch.zeros((total_iteration, n_loss),
                                   dtype=torch.float32,
                                   device=device)

    iiou_log: Optional[Tensor]
    intersections: Optional[Tensor]
    unions: Optional[Tensor]
    if compute_miou:
        iiou_log = torch.zeros((total_images, K),
                               dtype=torch.float32,
                               device=device)
        intersections = torch.zeros((total_images, K),
                                    dtype=torch.float32,
                                    device=device)
        unions = torch.zeros((total_images, K),
                             dtype=torch.float32,
                             device=device)
    else:
        iiou_log = None
        intersections = None
        unions = None

    three_d_dices: Optional[Tensor]
    if compute_3d_dice:
        three_d_dices = torch.zeros((total_iteration, K),
                                    dtype=torch.float32,
                                    device=device)
    else:
        three_d_dices = None

    hausdorff_log: Optional[Tensor]
    if compute_hausdorff:
        hausdorff_log = torch.zeros((total_images, K),
                                    dtype=torch.float32,
                                    device=device)
    else:
        hausdorff_log = None

    few_axis: bool = len(metric_axis) <= 3

    done_img: int = 0
    done_batch: int = 0
    tq_iter = tqdm_(total=total_iteration, desc=desc)
    for i, (loader, loss_fns, loss_weights) in enumerate(
            zip(loaders, list_loss_fns, list_loss_weights)):
        for data in loader:
            image: Tensor = data["images"].to(device)
            target: Tensor = data["gt"].to(device)
            spacings: Tensor = data["spacings"]  # Keep that one on CPU
            assert not target.requires_grad
            labels: List[Tensor] = [e.to(device) for e in data["labels"]]
            bounds: List[Tensor] = [e.to(device) for e in data["bounds"]]
            box_priors: List[List[Tuple[
                Tensor, Tensor]]]  # one more level for the batch
            box_priors = [[(m.to(device), b.to(device)) for (m, b) in B]
                          for B in data["box_priors"]]
            assert len(labels) == len(bounds)

            B, C, *_ = image.shape

            samplings: List[List[Tuple[slice]]] = data["samplings"]
            assert len(samplings) == B
            assert len(samplings[0][0]) == len(
                image[0, 0].shape), (samplings[0][0], image[0, 0].shape)

            probs_receptacle: Tensor = -torch.ones_like(
                target, dtype=torch.float32)  # -1 for unfilled
            mask_receptacle: Tensor = -torch.ones_like(
                target, dtype=torch.int32)  # -1 for unfilled

            # Use the sampling coordinates of the first batch item
            assert not (len(samplings[0]) > 1 and
                        B > 1), samplings  # No subsampling if batch size > 1
            loss_sub_log: Tensor = torch.zeros(
                (len(samplings[0]), len(loss_fns)),
                dtype=torch.float32,
                device=device)
            for k, sampling in enumerate(samplings[0]):
                img_sampling = [slice(0, B), slice(0, C)] + list(sampling)
                label_sampling = [slice(0, B), slice(0, K)] + list(sampling)
                assert len(img_sampling) == len(image.shape), (img_sampling,
                                                               image.shape)
                sub_img = image[img_sampling]

                # Reset gradients
                if optimizer:
                    optimizer.zero_grad()

                # Forward
                pred_logits: Tensor = net(sub_img)
                pred_probs: Tensor = F.softmax(temperature * pred_logits,
                                               dim=1)
                predicted_mask: Tensor = probs2one_hot(
                    pred_probs.detach())  # Used only for dice computation
                assert not predicted_mask.requires_grad

                probs_receptacle[label_sampling] = pred_probs[...]
                mask_receptacle[label_sampling] = predicted_mask[...]

                assert len(bounds) == len(loss_fns) == len(
                    loss_weights) == len(labels)
                ziped = zip(loss_fns, labels, loss_weights, bounds)
                losses = [
                    w * loss_fn(pred_probs, label[label_sampling], bound,
                                box_priors)
                    for loss_fn, label, w, bound in ziped
                ]
                loss = reduce(add, losses)
                assert loss.shape == (), loss.shape

                # Backward
                if optimizer:
                    loss.backward()
                    optimizer.step()

                # Compute and log metrics
                for j in range(len(loss_fns)):
                    loss_sub_log[k, j] = losses[j].detach()
            reduced_loss_sublog: Tensor = loss_sub_log.sum(dim=0)
            assert reduced_loss_sublog.shape == (len(loss_fns), ), (
                reduced_loss_sublog.shape, len(loss_fns))
            loss_log[done_batch, ...] = reduced_loss_sublog[...]
            del loss_sub_log

            sm_slice = slice(done_img,
                             done_img + B)  # Values only for current batch

            dices: Tensor = dice_coef(mask_receptacle, target)
            assert dices.shape == (B, K), (dices.shape, B, K)
            all_dices[sm_slice, ...] = dices

            if compute_3d_dice:
                three_d_DSC: Tensor = dice_batch(mask_receptacle, target)
                assert three_d_DSC.shape == (K, )

                three_d_dices[done_batch] = three_d_DSC  # type: ignore

            if compute_hausdorff:
                hausdorff_res: Tensor
                try:
                    hausdorff_res = hausdorff(mask_receptacle, target,
                                              spacings)
                except RuntimeError:
                    hausdorff_res = torch.zeros((B, K), device=device)
                assert hausdorff_res.shape == (B, K)
                hausdorff_log[sm_slice] = hausdorff_res  # type: ignore
            if compute_miou:
                IoUs: Tensor = iIoU(mask_receptacle, target)
                assert IoUs.shape == (B, K), IoUs.shape
                iiou_log[sm_slice] = IoUs  # type: ignore
                intersections[sm_slice] = inter_sum(mask_receptacle,
                                                    target)  # type: ignore
                unions[sm_slice] = union_sum(mask_receptacle,
                                             target)  # type: ignore

            # if False and target[0, 1].sum() > 0:  # Useful template for quick and dirty inspection
            #     import matplotlib.pyplot as plt
            #     from pprint import pprint
            #     from mpl_toolkits.axes_grid1 import ImageGrid
            #     from utils import soft_length

            #     print(data["filenames"])
            #     pprint(data["bounds"])
            #     pprint(soft_length(mask_receptacle))

            #     fig = plt.figure()
            #     fig.clear()

            #     grid = ImageGrid(fig, 211, nrows_ncols=(1, 2))

            #     grid[0].imshow(data["images"][0, 0], cmap="gray")
            #     grid[0].contour(data["gt"][0, 1], cmap='jet', alpha=.75, linewidths=2)

            #     grid[1].imshow(data["images"][0, 0], cmap="gray")
            #     grid[1].contour(mask_receptacle[0, 1], cmap='jet', alpha=.75, linewidths=2)
            #     plt.show()

            # Save images
            if savedir:
                with warnings.catch_warnings():
                    warnings.filterwarnings("ignore", category=UserWarning)
                    predicted_class: Tensor = probs2class(pred_probs)
                    save_images(predicted_class, data["filenames"], savedir,
                                mode, epc)

            # Logging
            big_slice = slice(0, done_img +
                              B)  # Value for current and previous batches

            dsc_dict: Dict
            if few_axis:
                dsc_dict = {
                    **{
                        f"DSC{n}": all_dices[big_slice, n].mean()
                        for n in metric_axis
                    },
                    **({
                        f"3d_DSC{n}": three_d_dices[:done_batch, n].mean()
                        for n in metric_axis
                    } if three_d_dices is not None else {})
                }
            else:
                dsc_dict = {}

            # dsc_dict = {f"DSC{n}": all_dices[big_slice, n].mean() for n in metric_axis} if few_axis else {}

            hauss_dict = {f"HD{n}": hausdorff_log[big_slice, n].mean() for n in metric_axis} \
                if hausdorff_log is not None and few_axis else {}

            miou_dict = {f"iIoU": iiou_log[big_slice, metric_axis].mean(),
                         f"mIoU": (intersections.sum(dim=0) / (unions.sum(dim=0) + 1e-10)).mean()} \
                if iiou_log is not None and intersections is not None and unions is not None else {}

            if len(metric_axis) > 1:
                mean_dict = {"DSC": all_dices[big_slice, metric_axis].mean()}
                if hausdorff_log:
                    mean_dict["HD"] = hausdorff_log[big_slice,
                                                    metric_axis].mean()
            else:
                mean_dict = {}

            stat_dict = {
                **miou_dict,
                **dsc_dict,
                **hauss_dict,
                **mean_dict, "loss": loss_log[:done_batch].mean()
            }
            nice_dict = {k: f"{v:.3f}" for (k, v) in stat_dict.items()}

            done_img += B
            done_batch += 1
            tq_iter.set_postfix({**nice_dict, "loader": str(i)})
            tq_iter.update(1)
    tq_iter.close()
    print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))

    mIoUs: Optional[Tensor]
    if intersections and unions:
        mIoUs = (intersections.sum(dim=0) / (unions.sum(dim=0) + 1e-10))
        assert mIoUs.shape == (K, ), mIoUs.shape
    else:
        mIoUs = None

    if not few_axis and False:
        print(f"DSC: {[f'{all_dices[:, n].mean():.3f}' for n in metric_axis]}")
        print(f"iIoU: {[f'{iiou_log[:, n].mean():.3f}' for n in metric_axis]}")
        if mIoUs:
            print(f"mIoU: {[f'{mIoUs[n]:.3f}' for n in metric_axis]}")

    return (
        loss_log.detach().cpu(), all_dices.detach().cpu(),
        hausdorff_log.detach().cpu() if hausdorff_log is not None else None,
        mIoUs.detach().cpu() if mIoUs is not None else None,
        three_d_dices.detach().cpu() if three_d_dices is not None else None)
Пример #12
0
def do_epoch(mode: str, net: Any, device: Any, loaders: list[DataLoader], epc: int,
             list_loss_fns: list[list[Callable]], list_loss_weights: list[list[float]], K: int,
             savedir: Path = None, optimizer: Any = None,
             metric_axis: list[int] = [1], requested_metrics: list[str] = None,
             temperature: float = 1) -> dict[str, Tensor]:
        assert mode in ["train", "val", "dual"]
        if requested_metrics is None:
                requested_metrics = []

        if mode == "train":
                net.train()
                desc = f">> Training   ({epc})"
        elif mode == "val":
                net.eval()
                desc = f">> Validation ({epc})"
        elif mode == "dual":
                net.eval()
                desc = f">> Dual       ({epc})"

        total_iteration: int = sum(len(loader) for loader in loaders)  # U
        total_images: int = sum(len(loader.dataset) for loader in loaders)  # D
        n_loss: int = max(map(len, list_loss_fns))

        epoch_metrics: dict[str, Tensor]
        epoch_metrics = {"dice": torch.zeros((total_images, K), dtype=torch.float32, device=device),
                         "loss": torch.zeros((total_iteration, n_loss), dtype=torch.float32, device=device)}

        if "3d_dsc" in requested_metrics:
                epoch_metrics["3d_dsc"] = torch.zeros((total_iteration, K), dtype=torch.float32, device=device)

        few_axis: bool = len(metric_axis) <= 4

        # time_log: np.ndarray = np.ndarray(total_iteration, dtype=np.float32)

        done_img: int = 0
        done_batch: int = 0
        tq_iter = tqdm_(total=total_iteration, desc=desc)
        for i, (loader, loss_fns, loss_weights) in enumerate(zip(loaders, list_loss_fns, list_loss_weights)):
                for data in loader:
                        # t0 = time()
                        image: Tensor = data["images"].to(device)
                        target: Tensor = data["gt"].to(device)
                        filenames: list[str] = data["filenames"]
                        assert not target.requires_grad

                        labels: list[Tensor] = [e.to(device) for e in data["labels"]]
                        bounds: list[Tensor] = [e.to(device) for e in data["bounds"]]
                        assert len(labels) == len(bounds)

                        B, C, *_ = image.shape

                        samplings: list[list[Tuple[slice]]] = data["samplings"]
                        assert len(samplings) == B
                        assert len(samplings[0][0]) == len(image[0, 0].shape), (samplings[0][0], image[0, 0].shape)

                        probs_receptacle: Tensor = - torch.ones_like(target, dtype=torch.float32)  # -1 for unfilled
                        mask_receptacle: Tensor = - torch.ones_like(target, dtype=torch.int32)  # -1 for unfilled

                        # Use the sampling coordinates of the first batch item
                        assert not (len(samplings[0]) > 1 and B > 1), samplings  # No subsampling if batch size > 1
                        loss_sub_log: Tensor = torch.zeros((len(samplings[0]), len(loss_fns)), 
                                                           dtype=torch.float32, device=device)
                        for k, sampling in enumerate(samplings[0]):
                                img_sampling = [slice(0, B), slice(0, C)] + list(sampling)
                                label_sampling = [slice(0, B), slice(0, K)] + list(sampling)
                                assert len(img_sampling) == len(image.shape), (img_sampling, image.shape)
                                sub_img = image[img_sampling]

                                # Reset gradients
                                if optimizer:
                                        optimizer.zero_grad()

                                # Forward
                                pred_logits: Tensor = net(sub_img)
                                pred_probs: Tensor = F.softmax(temperature * pred_logits, dim=1)

                                # Used only for dice computation:
                                predicted_mask: Tensor = probs2one_hot(pred_probs.detach())  
                                assert not predicted_mask.requires_grad

                                probs_receptacle[label_sampling] = pred_probs[...]
                                mask_receptacle[label_sampling] = predicted_mask[...]

                                assert len(bounds) == len(loss_fns) == len(loss_weights) == len(labels)
                                ziped = zip(loss_fns, labels, loss_weights, bounds)
                                losses = [w * loss_fn(pred_probs, label[label_sampling], bound, filenames)
                                          for loss_fn, label, w, bound in ziped]
                                loss = reduce(add, losses)
                                assert loss.shape == (), loss.shape

                                # Backward
                                if optimizer:
                                        loss.backward()
                                        optimizer.step()

                                # Compute and log metrics
                                for j in range(len(loss_fns)):
                                        loss_sub_log[k, j] = losses[j].detach()
                        reduced_loss_sublog: Tensor = loss_sub_log.sum(dim=0)
                        assert reduced_loss_sublog.shape == (len(loss_fns),), (reduced_loss_sublog.shape, len(loss_fns))
                        epoch_metrics["loss"][done_batch, ...] = reduced_loss_sublog[...]
                        del loss_sub_log

                        sm_slice = slice(done_img, done_img + B)  # Values only for current batch

                        dices: Tensor = dice_coef(mask_receptacle, target)
                        assert dices.shape == (B, K), (dices.shape, B, K)
                        epoch_metrics["dice"][sm_slice, ...] = dices

                        if "3d_dsc" in requested_metrics:
                                three_d_DSC: Tensor = dice_batch(mask_receptacle, target)
                                assert three_d_DSC.shape == (K,)

                                epoch_metrics["3d_dsc"][done_batch] = three_d_DSC  # type: ignore

                        # Save images
                        if savedir:
                                with warnings.catch_warnings():
                                        warnings.filterwarnings("ignore", category=UserWarning)
                                        predicted_class: Tensor = probs2class(pred_probs)
                                        save_images(predicted_class, 
                                                    data["filenames"], 
                                                    savedir / f"iter{epc:03d}" / mode)

                        # Logging
                        big_slice = slice(0, done_img + B)  # Value for current and previous batches

                        stat_dict: dict[str, Any] = {}
                        # The order matters for the final display -- it is easy to change

                        if few_axis:
                                stat_dict |= {f"DSC{n}": epoch_metrics["dice"][big_slice, n].mean()
                                              for n in metric_axis}

                                if "3d_dsc" in requested_metrics:
                                        stat_dict |= {f"3d_DSC{n}": epoch_metrics["3d_dsc"][:done_batch, n].mean()
                                                      for n in metric_axis}

                        if len(metric_axis) > 1:
                                stat_dict |= {"DSC": epoch_metrics["dice"][big_slice, metric_axis].mean()}

                        stat_dict |= {f"loss_{i}": epoch_metrics["loss"][:done_batch].mean(dim=0)[i] 
                                      for i in range(n_loss)}

                        nice_dict = {k: f"{v:.3f}" for (k, v) in stat_dict.items()}

                        # t1 = time()
                        # time_log[done_batch] = (t1 - t0)

                        done_img += B
                        done_batch += 1
                        tq_iter.set_postfix({**nice_dict, "loader": str(i)})
                        tq_iter.update(1)
        tq_iter.close()

        print(f"{desc} " + ', '.join(f"{k}={v}" for (k, v) in nice_dict.items()))

        return {k: v.detach().cpu() for (k, v) in epoch_metrics.items()}