最近在看miou的算法的时候碰到了个问题,有两种计算方式,实测miou的方式是voc pascal官方计算的方式,miou2有点不明意义,似乎是错的?

import random
import numpy as np


def fast_hist(a, b, n):
    # --------------------------------------------------------------------------------#
    #   a是转化成一维数组的标签,形状(H×W,);b是转化成一维数组的预测结果,形状(H×W,)
    # --------------------------------------------------------------------------------#
    k = (a >= 0) & (a < n)
    # --------------------------------------------------------------------------------#
    #   np.bincount计算了从0到n**2-1这n**2个数中每个数出现的次数,返回值形状(n, n)
    #   返回中,写对角线上的为分类正确的像素点
    # --------------------------------------------------------------------------------#
    return np.bincount(n * a[k].astype(int) + b[k], minlength=n ** 2).reshape(n, n)


def per_class_iu(hist):
    bing = np.maximum((hist.sum(1) + hist.sum(0) - np.diag(hist)), 1)
    return np.diag(hist) / bing


np.random.seed(11011)
data = np.random.randint(0, 2, (2, 2, 2))
data[1:, :, :] = 0
np.random.seed(110)
data2 = np.random.randint(0, 2, (2, 2, 2))
total_miou = 0
hist2 = np.zeros((2, 2), dtype=np.int64)
for k in range(data.shape[0]):
    pred = data[k]
    mask = data2[k]
    hist = fast_hist(pred, mask, 2)
    hist2 += hist
    miou = np.mean(per_class_iu(hist))
    total_miou += miou
miou = np.mean(per_class_iu(hist2))
miou2 = total_miou / data.shape[0]
print(miou, miou2)