在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)
'''