Keras, binary segmentation, adding weight to the loss function

I solve the problem of binary segmentation with Keras (w. Tf backend). How to add weight to the center of each area of ​​the mask?

I tried bone bones with added cv2.erode()but it doesn't work

def dice_coef_eroded(y_true, y_pred):
    kernel = (3, 3)
    y_true = cv2.erode(y_true.eval(), kernel, iterations=1)
    y_pred = cv2.erode(y_pred.eval(), kernel, iterations=1)
    y_true_f = K.flatten(y_true)
    y_pred_f = K.flatten(y_pred)
    intersection = K.sum(y_true_f * y_pred_f)
    return (2. * intersection + 1) / (K.sum(y_true_f) + K.sum(y_pred_f) + 1)

Keras 2.1.3, tensorflow 1.4

+1
source share
1 answer

Well, the solution I found is the following:

1) Create a method in your Iterator to extract the matrix of weights (with form = mask). The output must contain [image, mask, weight]

2) Create a lambda layer containing the loss function

3) Create an identity loss function

Example:

def weighted_binary_loss(X):
    import keras.backend as K
    import keras.layers.merge as merge
    y_pred, weights, y_true = X
    loss = K.binary_crossentropy(y_pred, y_true)
    loss = merge([loss, weights], mode='mul')
    return loss

def identity_loss(y_true, y_pred):
    return y_pred

def get_unet_w_lambda_loss(input_shape=(1024, 1024, 3), mask_shape=(1024, 1024, 1)):
    images = Input(input_shape)
    mask_weights = Input(mask_shape)
    true_masks = Input(mask_shape)
    ...
    y_pred = Conv2D(1, (1, 1), activation='sigmoid')(up1) #output of original unet
    loss = Lambda(weighted_binary_loss, output_shape=(1024, 1024, 1))([y_pred, mask_weights, true_masks])
    model = Model(inputs=[images, mask_weights, true_masks], outputs=loss)
0
source

Source: https://habr.com/ru/post/1671419/


All Articles