|
a |
|
b/Segmentation/metrics.py |
|
|
1 |
import numpy as np |
|
|
2 |
from keras import backend as K |
|
|
3 |
|
|
|
4 |
|
|
|
5 |
def dice_score(mask_gt, mask_pred): |
|
|
6 |
"""Computes soerensen-dice coefficient. |
|
|
7 |
|
|
|
8 |
compute the soerensen-dice coefficient between the ground truth mask `mask_gt` |
|
|
9 |
and the predicted mask `mask_pred`. |
|
|
10 |
|
|
|
11 |
Args: |
|
|
12 |
mask_gt: 3-dim Numpy array of type bool. The ground truth mask. |
|
|
13 |
mask_pred: 3-dim Numpy array of type bool. The predicted mask. |
|
|
14 |
|
|
|
15 |
Returns: |
|
|
16 |
the dice coeffcient as float. If both masks are empty, the result is NaN. |
|
|
17 |
""" |
|
|
18 |
volume_sum = mask_gt.sum() + mask_pred.sum() |
|
|
19 |
if volume_sum == 0: |
|
|
20 |
return np.NaN |
|
|
21 |
volume_intersect = (mask_gt & mask_pred).sum() |
|
|
22 |
return 2*volume_intersect / volume_sum |
|
|
23 |
|
|
|
24 |
def dice_coef(y_true, y_pred, smooth=1): |
|
|
25 |
""" |
|
|
26 |
Dice = (2*|X & Y|)/ (|X|+ |Y|) |
|
|
27 |
= 2*sum(|A*B|)/(sum(A^2)+sum(B^2)) |
|
|
28 |
ref: https://arxiv.org/pdf/1606.04797v1.pdf |
|
|
29 |
""" |
|
|
30 |
intersection = K.sum(K.abs(y_true * y_pred), axis=-1) |
|
|
31 |
return (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + K.sum(K.square(y_pred),-1) + smooth) |
|
|
32 |
|
|
|
33 |
def dice_coef_loss(y_true, y_pred): |
|
|
34 |
return 1-dice_coef(y_true, y_pred) |
|
|
35 |
|
|
|
36 |
def jacard_coef(y_true, y_pred): |
|
|
37 |
y_true_f = K.flatten(y_true) |
|
|
38 |
y_pred_f = K.flatten(y_pred) |
|
|
39 |
intersection = K.sum(y_true_f * y_pred_f) |
|
|
40 |
return (intersection + 1.0) / (K.sum(y_true_f) + K.sum(y_pred_f) - intersection + 1.0) |
|
|
41 |
|
|
|
42 |
|
|
|
43 |
def jacard_coef_loss(y_true, y_pred): |
|
|
44 |
return 1-jacard_coef(y_true, y_pred) |