我想知道如何为多类别细分计算骰子系数。
这里是将为二进制分割任务计算骰子系数的脚本。如何遍历每个班级并计算每个班级的骰子?
提前谢谢您
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_score,然后对所有类重复使用二进制映射,以获得多类骰子得分。
我假设您的图像/分段图的格式为(batch/index of image, height, width, class_map)
。
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}')