def calculate_iou(confusion_matrix):
    """
    calculate IoU (intersecion over union) for a given confusion matrix.
    """

    ious = []
    for index in range(confusion_matrix.shape[0]):
        true_positives = confusion_matrix[index, index]
        false_positives = confusion_matrix[:, index].sum() - true_positives
        false_negatives = confusion_matrix[index, :].sum() - true_positives

        denom = true_positives + false_positives + false_negatives

        # no entries, no iou..
        if denom == 0:
            iou = float('nan')
        else:
            iou = float(true_positives)/denom

        ious.append(iou)

    return ious