python 实现Dice Coefficient

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

在这里插入图片描述

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值