Pytorch 如何使用Python计算多类分割任务的骰子系数?
我想知道如何计算多类分割的骰子系数 下面是用于计算二进制分段任务的骰子系数的脚本。如何循环每个类并计算每个类的骰子 先谢谢你Pytorch 如何使用Python计算多类分割任务的骰子系数?,pytorch,dice,semantic-segmentation,Pytorch,Dice,Semantic Segmentation,我想知道如何计算多类分割的骰子系数 下面是用于计算二进制分段任务的骰子系数的脚本。如何循环每个类并计算每个类的骰子 先谢谢你 import numpy def dice_coeff(im1, im2, empty_score=1.0): im1 = numpy.asarray(im1).astype(numpy.bool) im2 = numpy.asarray(im2).astype(numpy.bool) if im1.shape != im2.shape
import numpy
def dice_coeff(im1, im2, empty_score=1.0):
im1 = numpy.asarray(im1).astype(numpy.bool)
im2 = numpy.asarray(im2).astype(numpy.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
im_sum = im1.sum() + im2.sum()
if im_sum == 0:
return empty_score
# Compute Dice coefficient
intersection = numpy.logical_and(im1, im2)
return (2. * intersection.sum() / im_sum)
您可以对二进制类使用dice_分数,然后对所有类重复使用二进制映射以获得多类dice分数 我假设您的图像/分割贴图的格式为
(图像的批/索引、高度、宽度、类别贴图)
import numpy as np
import matplotlib.pyplot as plt
def dice_coef(y_true, y_pred):
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
intersection = np.sum(y_true_f * y_pred_f)
smooth = 0.0001
return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
def dice_coef_multilabel(y_true, y_pred, numLabels):
dice=0
for index in range(numLabels):
dice += dice_coef(y_true[:,:,:,index], y_pred[:,:,:,index])
return dice/numLabels # taking average
num_class = 5
imgA = np.random.randint(low=0, high= 2, size=(5, 64, 64, num_class) ) # 5 images in batch, 64 by 64, num_classes map
imgB = np.random.randint(low=0, high= 2, size=(5, 64, 64, num_class) )
plt.imshow(imgA[0,:,:,0]) # for 0th image, class 0 map
plt.show()
plt.imshow(imgB[0,:,:,0]) # for 0th image, class 0 map
plt.show()
dice_score = dice_coef_multilabel(imgA, imgB, num_class)
print(f'For A and B {dice_score}')
dice_score = dice_coef_multilabel(imgA, imgA, num_class)
print(f'For A and A {dice_score}')