File size: 673 Bytes
fd4b932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import tensorflow as tf
from tensorflow.keras import backend as K

def boundary_loss(y_true, y_pred):
    """Additional loss focusing on boundaries"""
    # Compute gradients
    dy_true, dx_true = tf.image.image_gradients(y_true)
    dy_pred, dx_pred = tf.image.image_gradients(y_pred)
    
    # Compute boundary loss
    loss = tf.reduce_mean(tf.abs(dy_pred - dy_true) + tf.abs(dx_pred - dx_true))
    return loss * 0.5  # weight factor

def enhanced_binary_crossentropy(y_true, y_pred):
    """Combine standard BCE with boundary loss"""
    bce = tf.keras.losses.binary_crossentropy(y_true, y_pred)
    boundary = boundary_loss(y_true, y_pred)
    return bce + boundary