import torch


def get_IoU(predictions: torch.Tensor, labels: torch.Tensor, threshold: float = 0.5):
    """Code inspired by
    https://www.kaggle.com/iezepov/fast-iou-scoring-metric-in-pytorch-and-numpy
    """
    eps = 1e-6
    # assert N x H x W
    if len(predictions.shape) != 3:
        predictions.unsqueeze_(0)
    if len(labels.shape) != 3:
        labels.unsqueeze_(0)
    outputs = (predictions > threshold).int()
    labels = labels.int()
    # Will be zero if Truth=0 or Prediction=0
    intersection = (outputs & labels).float().sum((1, 2))
    # Will be zero if both are
    union = (outputs | labels).float().sum((1, 2))
    # We smooth our devision to avoid 0/0
    iou = (intersection + eps) / (union + eps)
    return iou.mean()