keras-team / keras-core

A multi-backend implementation of the Keras API, with support for TensorFlow, JAX, and PyTorch.
Apache License 2.0
1.27k stars 115 forks source link

Segmentation metrics #894

Closed emi-dm closed 10 months ago

emi-dm commented 10 months ago

Would it be possible to include default metrics in Keras for image segmentation? E.x Dice, IoU, HD, etc.

emi-dm commented 10 months ago

I tried this:

from keras_core import backend as K

def jaccard_distance_loss(y_true, y_pred, smooth=100):
    intersection = K.sum(K.sum(K.abs(y_true * y_pred), axis=-1))
    sum_ = K.sum(K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1))
    jac = (intersection + smooth) / (sum_ - intersection + smooth)
    return (1 - jac) * smooth

def dice_metric(y_pred, y_true):
    intersection = K.sum(K.sum(K.abs(y_true * y_pred), axis=-1))
    union = K.sum(K.sum(K.abs(y_true) + K.abs(y_pred), axis=-1))
    return 2*intersection / union

size = 10

y_true = np.zeros(shape=(size,size))
y_true[3:6,3:6] = 1

y_pred = np.zeros(shape=(size,size))
y_pred[3:5,3:5] = 1

loss = jaccard_distance_loss(y_true,y_pred)

metric = dice_metric(y_pred,y_true)

print(f"loss: {loss}")
print(f"dice_metric: {metric}")

It seems that keras_core does not yet have backend support. Can someone help me?

Thanks in advanced!

soumik12345 commented 10 months ago

@emi-research-dl This is probably better suited for KerasCV

emi-dm commented 10 months ago

@soumik12345 Totally agree!!