如何计算平均交并比(mean Intersection over Union,简称mean IU)分数,就像这篇论文中描述的那样?
Long, Jonathan, Evan Shelhamer和Trevor Darrell所撰写的"全卷积网络用于语义分割"。
Long, Jonathan, Evan Shelhamer和Trevor Darrell所撰写的"全卷积网络用于语义分割"。
每个类别的交叉并集(Intersection over Union,IU)得分如下:
真阳性 / (真阳性 + 假阳性 + 假阴性)
平均IU指的是所有类别的平均值。
关于论文中的符号表示:
n_ij:被预测为属于类别j的类别i像素数量。因此对于类别i:
您可以在Pascak DevKit的这里找到直接计算此方法的Matlab代码。
真正例 / (真正例 + 假正例 + 假负例)
,接下来该怎么办?我应该计算所有图像IOU的平均值吗?如果在某些图像上某些类别未出现且未被预测,则 I = 0
和 U = 0
,那么在计算IOU平均值时,我是否需要为每个类别单独制作“计数器”? - mrgloom from sklearn.metrics import confusion_matrix
import numpy as np
def compute_iou(y_pred, y_true):
# ytrue, ypred is a flatten vector
y_pred = y_pred.flatten()
y_true = y_true.flatten()
current = confusion_matrix(y_true, y_pred, labels=[0, 1])
# compute mean iou
intersection = np.diag(current)
ground_truth_set = current.sum(axis=1)
predicted_set = current.sum(axis=0)
union = ground_truth_set + predicted_set - intersection
IoU = intersection / union.astype(np.float32)
return np.mean(IoU)
return np.nanmean
,因为0可能是一个有效的混淆矩阵(我们正确地从未尝试预测任何东西,留下0的混淆)。 - lee penkman这应该会有所帮助
def computeIoU(y_pred_batch, y_true_batch):
return np.mean(np.asarray([pixelAccuracy(y_pred_batch[i], y_true_batch[i]) for i in range(len(y_true_batch))]))
def pixelAccuracy(y_pred, y_true):
y_pred = np.argmax(np.reshape(y_pred,[N_CLASSES_PASCAL,img_rows,img_cols]),axis=0)
y_true = np.argmax(np.reshape(y_true,[N_CLASSES_PASCAL,img_rows,img_cols]),axis=0)
y_pred = y_pred * (y_true>0)
return 1.0 * np.sum((y_pred==y_true)*(y_true>0)) / np.sum(y_true>0)
y_pred
的形状为 n_classes*h*w
,我们想将它们转换成一张单独的图像,其中像素值等于该像素处的类别,因此我们沿着类别轴取 arg max。 - stochastic_zeitgeist可以使用jaccard_similarity_score
(参见如何从分割掩模中找到IoU?)来获得与@Alex-zhai上面的代码相同的结果:
import numpy as np
from sklearn.metrics import jaccard_score
y_true = np.array([[0, 1, 1],
[1, 1, 0]])
y_pred = np.array([[1, 1, 1],
[1, 0, 0]])
labels = [0, 1]
jaccards = []
for label in labels:
jaccard = jaccard_score(y_pred.flatten(),y_true.flatten(), pos_label=label)
jaccards.append(jaccard)
print(f'avg={np.mean(jaccards)}')