pixel accuracy, mean accuracy, mean IU, frequency weighted IU
详解转自:https://blog.csdn.net/u014593748/article/details/71698246
代码测试
import numpy as np
class Evaluator(object):
def __init__(self, num_class):
self.num_class = num_class
self.confusion_matrix = np.zeros((self.num_class,)*2)
def Pixel_Accuracy(self):
Acc = np.diag(self.confusion_matrix).sum() / self.confusion_matrix.sum()
return Acc
def Pixel_Accuracy_Class(self):
Acc = np.diag(self.confusion_matrix) / self.confusion_matrix.sum(axis=1)
print('-----------Acc of each classes-----------')
print("yes : %.6f" % (Acc[0] * 100.0), "%\t")
print("no : %.6f" % (Acc[1] * 100.0), "%\t")
if self.num_class == 3:
print("small obstacles: %.6f" % (Acc[2] * 100.0), "%\t")
Acc = np.nanmean(Acc)
return Acc
def Mean_Intersection_over_Union(self):
MIoU = np.diag(self.confusion_matrix) / (
np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -
np.diag(self.confusion_matrix))
print('-----------IoU of each classes-----------')
print("yes : %.6f" % (MIoU[0] * 100.0), "%\t")
print("no : %.6f" % (MIoU[1] * 100.0), "%\t")
if self.num_class == 3:
print("small obstacles: %.6f" % (MIoU[2] * 100.0), "%\t")
MIoU = np.nanmean(MIoU)
return MIoU
def Frequency_Weighted_Intersection_over_Union(self):
freq = np.sum(self.confusion_matrix, axis=1) / np.sum(self.confusion_matrix)
iu = np.diag(self.confusion_matrix) / (
np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -
np.diag(self.confusion_matrix))
FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()
return FWIoU
def _generate_matrix(self, gt_image, pre_image):
mask = (gt_image >= 0) & (gt_image < self.num_class)
label = self.num_class * gt_image[mask].astype('int') + pre_image[mask]
count = np.bincount(label, minlength=self.num_class**2)
confusion_matrix = count.reshape(self.num_class, self.num_class)
return confusion_matrix
def add_batch(self, gt_image, pre_image):
assert gt_image.shape == pre_image.shape
self.confusion_matrix += self._generate_matrix(gt_image, pre_image)
def reset(self):
self.confusion_matrix = np.zeros((self.num_class,) * 2)
if __name__ == '__main__':
import torch
eva = Evaluator(3)
x = [[2, 1, 0],[1, 2, 0]]
y = [[2, 1, 0], [1, 2, 1]]
x = np.array(x)
y = np.array(y)
print(x)
print(y)
print('====================')
confusion_matrix = eva._generate_matrix(x,y)
print(confusion_matrix)
eva.add_batch(x, y)
PA = eva.Pixel_Accuracy()
print("PA:",PA)
Acc = eva.Pixel_Accuracy_Class()
print("Acc:",Acc)
MIoU = eva.Mean_Intersection_over_Union()
print("MIoU:",MIoU)
print('====================')
FWIoU = eva.Frequency_Weighted_Intersection_over_Union()
print("FWIoU:",FWIoU)
|