I am new to Keras. I need some help in writing a custom loss function in keras with TensorFlow backend for the following loss equation.
The parameters passed to the loss function are :
-
y_true
would be of shape(batch_size, N, 2)
. Here, we are passing N(x, y)
coordinates in each sample in the batch. y_pred
would be of shape(batch_size, 256, 256, N)
. Here, we are passing N predicted heatmaps of256 x 256
pixels in each sample in the batch.
i
∈ [0, 255]
j
∈ [0, 255]
Mn(i, j)
represents value at pixel location (i, j)
for the nth predicted heatmap.
Mn∼(i, j) = Guassian2D((i, j), y_truen, std)
where
std = standard deviation
, same standard deviation for both the dimensions (5 px).
y_truen is the nth (x, y) coordinate. This is the mean.
For details of this, please check the l2 loss described in this paper Human Pose Estimation.
Note : I mentioned batch_size in shape of y_true and y_pred. I assumed that Keras calls loss function on the entire batch and not on individual samples in the batch. Correct me if I am wrong.
def l2_loss(y_true, y_pred):
loss = 0
n = y_true.shape[0]
for j in range(n):
for i in range(num_joints):
yv, xv = tf.meshgrid(tf.arange(0, im_height), tf.arange(0, im_width))
z = np.array([xv, yv]).transpose(1, 2, 0)
ground = np.exp(-0.5*(((z - y_true[j, i, :])**2).sum(axis=2))/(sigma**2))
loss = loss + np.sum((ground - y_pred[j,:, :, i])**2)
return loss/num_joints
This is the code I have writen so far. I know that this won't run as we can't use direct numpy ndarrays inside a keras loss function. Also, I need to eliminate loops!