forked from alexanderkroner/saliency
-
Notifications
You must be signed in to change notification settings - Fork 4
/
loss.py
executable file
·30 lines (22 loc) · 1.16 KB
/
loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import tensorflow as tf
def kld(y_true, y_pred, eps=1e-7):
"""This function computes the Kullback-Leibler divergence between ground
truth saliency maps and their predictions. Values are first divided by
their sum for each image to yield a distribution that adds to 1.
Args:
y_true (tensor, float32): A 4d tensor that holds the ground truth
saliency maps with values between 0 and 255.
y_pred (tensor, float32): A 4d tensor that holds the predicted saliency
maps with values between 0 and 1.
eps (scalar, float, optional): A small factor to avoid numerical
instabilities. Defaults to 1e-7.
Returns:
tensor, float32: A 0D tensor that holds the averaged error.
"""
sum_per_image = tf.reduce_sum(y_true, axis=(1, 2, 3), keep_dims=True)
y_true /= eps + sum_per_image
sum_per_image = tf.reduce_sum(y_pred, axis=(1, 2, 3), keep_dims=True)
y_pred /= eps + sum_per_image
loss = y_true * tf.log(eps + y_true / (eps + y_pred))
loss = tf.reduce_mean(tf.reduce_sum(loss, axis=(1, 2, 3)))
return loss