D i c e C o e f f i c i e n t Dice Coefficient DiceCoefficient
Dice coefficient 是 Lee R. Dice 在1945年为评估生物种群提出的一种度量方法(Dice, Lee R. “Measures of the amount of ecologic association between species.” Ecology 26.3 (1945): 297-302.)。后来不同领域的学者都将其引入到自己的专业
一 公式
注意下述设计只能是二分类,就是label和预测只能是0和1
实现
单张图片计算
import numpy as np
gt_image = np.array([
[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
])
pre_image = np.array([
[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,1]
])
def dice_coefficient(y_true, y_pred):
smooth = 1
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
intersection = np.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
def dice_average_sets(y_true, y_pred):
assert y_true.shape[0]==y_pred.shape[0], "you should use same size data"
dice = []
for i in range(y_true.shape[0]):
dice.append(dice_coefficient(y_true[i], y_pred[i]))
print(np.mean(dice))
return dice
dice_coefficient(gt_image,pre_image)
计算多张dice均值
gt_image = np.array([
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
])
pre_image = np.array([
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
])
def dice_average_sets(y_true, y_pred):
assert y_true.shape[0]==y_pred.shape[0], "you should use same size data"
dice = []
for i in range(y_true.shape[0]):
dice.append(dice_coefficient(y_true[i], y_pred[i]))
print(np.mean(dice))
return dice
dice_coefficient(gt_image,pre_image)
综合多张计算方式二
gt_image = np.array([
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
])
pre_image = np.array([
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
])
def DiceCoefficient(y_true, y_pred):
dims=(-2,-1)
smooth=1.
tp = (y_true * y_pred).sum(dims)
fp = (y_true * (1 - y_pred)).sum(dims)
fn = ((1 - y_true) * y_pred).sum(dims)
dc = (2 * tp + smooth) / (2 * tp + fp + fn + smooth)
dc = dc.mean()
return dc