深度学习100问 Author:louwill Machine Learning Lab 像素准确率(PA) 平均像素准确率(MPA) 平均交并比(MIoU) 频权交并比(FWIoU) Dice系数 from keras import backend as K
def dice_coef(y_true, y_pred, smooth=1): ''' Dice = (2*|X & Y|)/ (|X|+ |Y|)
= 2*sum(|A*B|)/(sum(A^2)+sum(B^2)) ''' y_true = K.flatten(y_true) y_pred = K.flatten(y_pred) intersection = K.sum(K.abs(y_true * y_pred)) dice = (2. * intersection + smooth) / (K.sum(K.square(y_true)) + K.sum(K.square(y_pred)) + smooth) return dice
import numpy as np
class SegMetrics(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 Mean_Pixel_Accuracy(self): # Precision=TP/(TP+FP) Acc = np.diag(self.confusion_matrix) / self.confusion_matrix.sum(axis=1) Acc = np.nanmean(Acc) return Acc
# 平均IoU def Mean_IoU(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)) MIoU = np.nanmean(MIoU) return MIoU
# 频权IoU def Freq_Weighted_IoU(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
# Dice系数 def dice(self): dice_coef = 2*np.diag(self.confusion_matrix) / ( np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0)) return dice_coef
# 生成混淆矩阵 def _generate_matrix(self, gt_image, pre_image): mask = (gt_image >= 0) & (gt_image < self.num_class) label = self.num_class * gt_image[mask] + 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) 参考资料: https://www./evaluating-image-segmentation-models/ https://github.com/xtudbxk/semantic-segmentation-metrics |
|
来自: LibraryPKU > 《机器学习》