mIou的GPU高效实现算法

在数据加载时,将语义标签转为二值矩阵

由于框架实现了数据异步加载,所以在数据加载阶段的以下代码不会影响GPU计算速度。

        # 图像标签的稠密矩阵
        shape = img_l.shape  # img_l为图像标签
        img_ld = numpy.zeros((19,) + shape)  # img_ld为稠密矩阵
        for i in range(19):
            img_ld[i] = (img_l == i)
        img_ld.astype('float32')
        

mIou计算函数

应用在pytorch框架中

class mIou(nn.Module):

    def __init__(self):
        super().__init__()

    def forward(self, outputs, targets):
        ma = torch.amax(outputs, dim=1)
        outputs = outputs - ma
        outputs = (outputs == 0).type_as(outputs)

        a = outputs + targets

        tt = torch.sum(a == 2, dim=[0, 2, 3])
        tf = torch.sum(a > 0, dim=[0, 2, 3])

        tt[tf == 0] = 1
        tf[tf == 0] = 1

        return torch.mean(tt / tf)

        

加入mIou评估

实例化评估函数

evaluate = util.loss.mIou().cuda()  # 评估函数
m = 0

在训练中计算miou

    e = evaluate(y_, z)

    m += e.item()
    if batch % 30 == 0:  # 每30个批次进行一次评估
        print('loss:', f / 30, 'mIou:', m / 30)
        m = 0

如有更高效的算法或不足之处欢迎留言评论

猜你喜欢

转载自blog.csdn.net/qq_40092672/article/details/120129349