code to calculate dice score

Solutions on MaxInterview for code to calculate dice score by the best coders in the world

showing results for - "code to calculate dice score"
Gianluca
30 May 2017
1import numpy as np
2np.random.seed(0)
3true = np.random.rand(10, 5, 5, 4)>0.5
4pred = np.random.rand(10, 5, 5, 4)>0.5
5
6def single_dice_coef(y_true, y_pred_bin):
7    # shape of y_true and y_pred_bin: (height, width)
8    intersection = np.sum(y_true * y_pred_bin)
9    if (np.sum(y_true)==0) and (np.sum(y_pred_bin)==0):
10        return 1
11    return (2*intersection) / (np.sum(y_true) + np.sum(y_pred_bin))
12
13def mean_dice_coef(y_true, y_pred_bin):
14    # shape of y_true and y_pred_bin: (n_samples, height, width, n_channels)
15    batch_size = y_true.shape[0]
16    channel_num = y_true.shape[-1]
17    mean_dice_channel = 0.
18    for i in range(batch_size):
19        for j in range(channel_num):
20            channel_dice = single_dice_coef(y_true[i, :, :, j], y_pred_bin[i, :, :, j])
21            mean_dice_channel += channel_dice/(channel_num*batch_size)
22    return mean_dice_channel
23
24def dice_coef2(y_true, y_pred):
25    y_true_f = y_true.flatten()
26    y_pred_f = y_pred.flatten()
27    union = np.sum(y_true_f) + np.sum(y_pred_f)
28    if union==0: return 1
29    intersection = np.sum(y_true_f * y_pred_f)
30    return 2. * intersection / union
31
32print(mean_dice_coef(true, pred))
33print(dice_coef2(true, pred))
34
35# 0.4884357140842496
36# 0.499001996007984
37