frozencherry/Forgery-Localization-App
1
1import tensorflow as tf
2
3
4def dice_coefficient(y_true, y_pred, smooth=1e-5):
5 intersection = tf.reduce_sum(y_true * y_pred)
6 union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
7 dice = (2. * intersection + smooth) / (union + smooth)
8 return dice
9
10def dice_coef_loss(y_true, y_pred):
11 return 1-dice_coefficient(y_true, y_pred)
12
13def iou(y_true, y_pred, smooth=1):
14 intersection = tf.reduce_sum(y_true * y_pred)
15 union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) - intersection
16 iou = (intersection + smooth) / (union + smooth)
17 return iou
18
19def iou_loss(y_true, y_pred):
20 return 1 - iou(y_true, y_pred)
21
22def accuracy(y_true, y_pred):
23 correct_pixels = tf.reduce_sum(tf.cast(tf.equal(y_true, tf.round(y_pred)), dtype=tf.float32))
24 total_pixels = tf.cast(tf.reduce_prod(tf.shape(y_true)), dtype=tf.float32)
25 accuracy = correct_pixels / total_pixels
26 return accuracy
27
28def weighted_dice_bce_loss(y_true, y_pred, bce_weight=0.5, smooth=1):
29 y_true = tf.cast(y_true, dtype=tf.float32)
30 y_pred = tf.cast(y_pred, dtype=tf.float32)
31
32 intersection = tf.reduce_sum(y_true * y_pred)
33 dice = (2. * intersection + smooth) / (tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) + smooth)
34 dice_loss = 1 - dice
35
36 bce_loss = tf.reduce_mean(tf.keras.losses.binary_crossentropy(y_true, y_pred))
37
38 total_loss = bce_weight * bce_loss + (1 - bce_weight) * dice_loss
39 return total_loss