Discussions>Keras IoU implementation>

Keras IoU implementation

Are there any implementations of Intersection over Union metric in Keras 2.1.*?

2 votesJO242.00
1 Answers
def mean_iou(y_true, y_pred):
    y_pred = K.cast(K.greater(y_pred, .5), dtype='float32') # .5 is the threshold
    inter = K.sum(K.sum(K.squeeze(y_true * y_pred, axis=3), axis=2), axis=1)
    union = K.sum(K.sum(K.squeeze(y_true + y_pred, axis=3), axis=2), axis=1) - inter
    return K.mean((inter + K.epsilon()) / (union + K.epsilon()))

It's not difficult. Remember we are talking about masks and y_true, y_pred are matrices with 0 or 1. The operations are pixelwise

Intersection = y_true * y_pred // all pixel locations, which are 1 for both y_true and y_pred

Union = y_true + y_pred - Intersection // combines all pixel locations from y_true and y_pred. If we just add y_true and y_pred we will calculate their common part twice, that's why we subtract their intersection. 

the sum function and axis arguments are just parameters and it's a way to understand the shapes of y_true and y_pred.


How did you know this?

Couldn't find what you were looking for?and we will find an expert to answer.
How helpful was this page?