2

我正在做一个关于多类语义分割的项目。我制定了一个模型,该模型通过降低损失值来输出漂亮的下降分割图像。但是,我无法在诸如 meanIoU 或 Dice 系数之类的指标中评估模型性能。在二元语义分割的情况下,很容易将阈值设置为 0.5,将输出分类为对象或背景,但在多类语义分割的情况下不起作用。您能否告诉我如何在上述指标上获得模型性能?任何帮助将不胜感激!

顺便说一句,我正在使用 PyTorch 框架和 CamVid 数据集。

4

1 回答 1

6

如果有人对此答案感兴趣,请同时查看此问题。该问题的作者指出,mIoU 可以以不同的方式计算(并且该方法在文献中更被接受)。因此,在将实现用于任何正式发布之前,请考虑这一点。不幸的是,我目前无法使用这些详细信息更新此答案,但将来可能会这样做。

原答案:

下面给出的是 PyTorch 中平均 IoU(联合交集)的实现。

def mIOU(label, pred, num_classes=19):
    pred = F.softmax(pred, dim=1)              
    pred = torch.argmax(pred, dim=1).squeeze(1)
    iou_list = list()
    present_iou_list = list()

    pred = pred.view(-1)
    label = label.view(-1)
    # Note: Following for loop goes from 0 to (num_classes-1)
    # and ignore_index is num_classes, thus ignore_index is
    # not considered in computation of IoU.
    for sem_class in range(num_classes):
        pred_inds = (pred == sem_class)
        target_inds = (label == sem_class)
        if target_inds.long().sum().item() == 0:
            iou_now = float('nan')
        else: 
            intersection_now = (pred_inds[target_inds]).long().sum().item()
            union_now = pred_inds.long().sum().item() + target_inds.long().sum().item() - intersection_now
            iou_now = float(intersection_now) / float(union_now)
            present_iou_list.append(iou_now)
        iou_list.append(iou_now)
    return np.mean(present_iou_list)

您的模型的预测将采用 one-hot 形式,因此首先采用 softmax(如果您的模型还没有),然后argmax获取每个像素处概率最高的索引。然后,我们计算每个类的 IoU(并在最后取平均值)。

我们可以将预测和标签重塑为一维向量(我读到它使计算更快)。pred_inds = (pred == sem_class)对于每个类,我们首先使用和识别该类的索引target_inds = (label == sem_class)。结果pred_indstarget_inds将在标记为该特定类的像素处具有 1,而对于任何其他类,将具有 0。

然后,目标可能根本不包含该特定类。这将使该类的 IoU 计算无效,因为它不存在于目标中。因此,您为此类类分配了一个 NaN IoU(以便您稍后可以识别它们)并且不让它们参与均值的计算。

如果特定类存在于目标中,pred_inds[target_inds]则将给出一个 1 和 0 的向量,其中 1 的索引是预测和目标相等的那些,否则为零。取所有元素的总和将给我们交集。

如果我们添加 和 的所有元素pred_indstarget_inds我们将得到该特定类的像素的并集 + 交集。所以,我们减去已经计算的交集得到并集。然后,我们可以划分交集和并集以获取该特定类的 IoU 并将其添加到有效 IoU 列表中。

最后,你取整个列表的平均值来获得 mIoU。如果你想要骰子系数,你可以用类似的方式计算它。

于 2020-06-19T06:46:43.347 回答