目录
1. 介绍
2. dice 和 iou 的联系
3. 代码实现
3.1 dice
3.2 iou
3.3 test
3.4 dice 和 iou 的关系曲线
4. 代码
1. 介绍
dice 和 iou 都是衡量两个集合之间相似性的度量
dice计算公式:
iou计算公式:
iou的集合理解:
iou 其实就是两个区域的 overlap 部分和 union 部分的比值,也就是两个集合的交集 / 并集
dice 的分母不是并集,因为dice的分母是两个区域的和,A+B = A + B - A∩B,所以dice的分母其实是少减去了一个 A∩B,所以就让分子的 A∩B(交集) 扩大2倍
2. dice 和 iou 的联系
如果将两个集合间的关系划分的更细一点,即这种形式:
那么 A∩B = TP , A∪B = FN + TP + FP ,A+B = FN + TP +TP + FP
dice :
iou :
那么根据变形,可以得出:
3. 代码实现
|A ∩ B| = A * B 的 和 = 两个区域乘积的和
|A| + |B| = A + B 的和 = 两个区域相加的总和
|A∪B| = |A| + |B| - |A ∩ B| = 两个区域相交的总和 - 两个区域相乘的和
3.1 dice
dice 的实现
# Dice
def Dice(pred,true):
intersection = pred * true # 计算交集 pred ∩ true
temp = pred + true # pred + true
smooth = 1e-8 # 防止分母为 0
dice_score = 2*intersection.sum() / (temp.sum() + smooth)
return dice_score
intersection 为两个区域的交集,即两个区域的乘积
temp 为两个区域的和,(注:这里不是并集,因为没有减去相交的部分)
3.2 iou
iou 的实现
# Iou
def Iou(pred,true):
intersection = pred * true # 计算交集 pred ∩ true
temp = pred + true # pred + true
union = temp - intersection # 计算并集:A ∪ B = A + B - A ∩ B
smooth = 1e-8 # 防止分母为 0
iou_score = intersection.sum() / (union.sum() + smooth)
return iou_score
intersection 为两个区域的交集,即两个区域的乘积
temp 为两个区域的和,(注:这里不是并集,因为没有减去相交的部分)
union 为两个区域的并集
3.3 test
预测:
# prediction
predict = torch.tensor([0.01,0.03,0.02,0.02,0.05,0.12,0.09,0.07,0.89,0.85,0.88,0.91,0.99,0.97,0.95,0.97]).reshape(1,1,4,4)
'''
tensor([[[[0.0100, 0.0300, 0.0200, 0.0200],
[0.0500, 0.1200, 0.0900, 0.0700],
[0.8900, 0.8500, 0.8800, 0.9100],
[0.9900, 0.9700, 0.9500, 0.9700]]]])
'''
label:
# label
label = torch.tensor([0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]).reshape(1,1,4,4)
'''
tensor([[[[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1],
[1, 1, 1, 1]]]])
'''
计算结果:
公式可知,dice和iou的关系为:
验证可知:
注:有些细微的差异是smooth所导致
3.4 dice 和 iou 的关系曲线
有公式可知,dice 和 iou 的关系公式如下:
关系曲线如图:
4. 代码
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import torch
import numpy as np
import matplotlib.pyplot as plt
# prediction
predict = torch.tensor([0.01,0.03,0.02,0.02,0.05,0.12,0.09,0.07,0.89,0.85,0.88,0.91,0.99,0.97,0.95,0.97]).reshape(1,1,4,4)
'''
tensor([[[[0.0100, 0.0300, 0.0200, 0.0200],
[0.0500, 0.1200, 0.0900, 0.0700],
[0.8900, 0.8500, 0.8800, 0.9100],
[0.9900, 0.9700, 0.9500, 0.9700]]]])
'''
# label
label = torch.tensor([0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]).reshape(1,1,4,4)
'''
tensor([[[[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1],
[1, 1, 1, 1]]]])
'''
# Dice
def Dice(pred,true):
intersection = pred * true # 计算交集 pred ∩ true
temp = pred + true # pred + true
smooth = 1e-8 # 防止分母为 0
dice_score = 2*intersection.sum() / (temp.sum() + smooth)
return dice_score
# Iou
def Iou(pred,true):
intersection = pred * true # 计算交集 pred ∩ true
temp = pred + true # pred + true
union = temp - intersection # 计算并集:A ∪ B = A + B - A ∩ B
smooth = 1e-8 # 防止分母为 0
iou_score = intersection.sum() / (union.sum() + smooth)
return iou_score
# dice 和 iou 的换算
def dice_and_iou(x):
y = x / (2 - x)
return y
dice = np.arange(0,1,0.001)
iou = dice_and_iou(dice)
plt.plot(dice,iou)
plt.xlabel('dice')
plt.ylabel('iou')
plt.show()