[深度学习从入门到女装]detectron2源码阅读-混淆矩阵计算

在detectron2中对于分类问题的混淆矩阵计算部分代码如下:

//混淆矩阵计算
self._conf_matrix = np.zeros((self._N, self._N), dtype=np.int64)
output = output["sem_seg"].argmax(dim=0).to(self._cpu_device)
pred = np.array(output, dtype=np.int)
gt[gt == self._ignore_label] = self._num_classes
self._conf_matrix += np.bincount(
                self._N * pred.reshape(-1) + gt.reshape(-1), minlength=self._N ** 2
            ).reshape(self._N, self._N)



//准确率等指标计算
acc = np.zeros(self._num_classes, dtype=np.float)
iou = np.zeros(self._num_classes, dtype=np.float)
tp = self._conf_matrix.diagonal()[:-1].astype(np.float)
pos_gt = np.sum(self._conf_matrix[:-1, :-1], axis=0).astype(np.float)
class_weights = pos_gt / np.sum(pos_gt)
pos_pred = np.sum(self._conf_matrix[:-1, :-1], axis=1).astype(np.float)
acc_valid = pos_gt > 0
acc[acc_valid] = tp[acc_valid] / pos_gt[acc_valid]
iou_valid = (pos_gt + pos_pred) > 0
union = pos_gt + pos_pred - tp
iou[acc_valid] = tp[acc_valid] / union[acc_valid]
macc = np.sum(acc) / np.sum(acc_valid)
miou = np.sum(iou) / np.sum(iou_valid)
fiou = np.sum(iou * class_weights)
pacc = np.sum(tp) / np.sum(pos_gt)

通过使用N*pred+gt的映射到N**2的空间上,再通过矩阵形式的展开,便得到了混淆矩阵的计算结果

举个栗子看一下

import numpy as np
pred=np.array([[1,2,3],[2,0,1],[3,2,1]])
'''
array([[1, 2, 3],
       [2, 0, 1],
       [3, 2, 1]])
'''

gt=np.array([[1,2,3],[1,2,3],[3,2,0]])
'''
array([[1, 2, 3],
       [1, 2, 3],
       [3, 2, 0]])
'''

matrix=np.bincount(4*pred.reshape(-1)+gt.reshape(-1),minlength=4*2).reshape(4,4)
'''
array([[0, 0, 1, 0],
       [1, 1, 0, 1],
       [0, 1, 2, 0],
       [0, 0, 0, 2]], dtype=int64)
'''

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值