def batch_pix_accuracy(output, target):
"""PixAcc"""
# inputs are NDarray, output 4D, target 3D
# the category -1 is ignored class, typically for background / boundary
predict = np.argmax(output.asnumpy(), 1).astype('int64') + 1
target = target.asnumpy().astype('int64') + 1
pixel_labeled = np.sum(target > 0)
pixel_correct = np.sum((predict == target)*(target > 0))
assert pixel_correct <= pixel_labeled, "Correct area should be smaller than Labeled"
return pixel_correct, pixel_labeled
output
这个是 Pred,是一个 N x C x H x W 的张量,target
是 label,是一个 N x H x W 的张量
pixel_labeled = np.sum(target > 0)
这句话的意思其实暗含了在 target 中的 ignore_label 要小于等于 -1 的负整数;因此其实是可以有多个 ignore_label 的,不管在 predict 中他们的 index 是多少,由于 target > 0
的存在,只要 target 中他们小于等于 0,就没关系;但是一定要把不是 ignore_label 的类别在 target 中设置成与 predict 中的这些 index 一致
np.argmax(output.asnumpy(), 1)
就是返回 C 上面最大值的 index,那么就是 0,1,2,3 这样的自然数(都非负),+ 1
后那就是 1, 2, 3, 4... 这里其实是将类别和 index 挂钩,强制类别必须是0,1,2,3...
- target 的类别来自于 Dataset,但因为要和前面的 predict 中的类别判断是否相同,所以也强制规定了不是 ignore_label 的类别在 target 中设置成与 predict 中的这些 index 一致
- 假设两类,target 中 背景是 -1,想要忽略掉,目标是 1,那么在
pixel_labeled = np.sum(target > 0)
中就只计算目标元素的个数,pixel_correct = np.sum((predict == target)*(target > 0))
同样也只计算目标元素正确的个数
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are NDarray, output 4D, target 3D
# the category -1 is ignored class, typically for background / boundary
mini = 1
maxi = nclass
nbins = nclass
- 这里的
mini
, maxi
, nbins
都是用于下面的 np.histogram
函数中。
nbins = nclass
,ignore label 是否要计入 nclass?如果是在 Net 的 Predictor 中,nclass 一定是包含 ignore label 的。但是在 Metric 的 batch_intersection_union
这里,area_inter
这些是只统计不是 ignore label 的类别。因此,在这里 ignore label 是不需要计入 nclass 的。如果前景背景二分类且要忽略背景的话,nclass 就是 1.
mini = 1
这里其实表示了不被 ignore 的 label 的最小的类号是要为 0(考虑到 predict 那里会有个类号 + 1),因此如果前景背景二分类且要忽略背景的话,比较合适的 Groundtruth Label 设置应该是背景为 -1,前景为 0. 但这里完全不对 predict 里面 不被忽略的最小的就是 2,对应在 Groundtruth Label 中前景应该为 1.
# areas of intersection and union
area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi))
area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi))
area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi))