Custom conditional Keras metric

I am trying to create the following metric for my neural network using keras

$$s = \left\{ \begin{array}{ll} \sum_{i=1}^{n} e^{\frac{-d_i}{10}}-1 & \quad d < 0 \\ \sum_{i=1}^{n} e^{\frac{d_i}{13}}-1 & \quad d \geq 0 \end{array} \right.$$ where $d_i=y_{pred}-y_{true}$

and both $y_{pred}$ and $y_{true}$ are vectors

With the following code:

import keras.backend as K

def score(y_true, y_pred):
d=(y_pred - y_true)
if d<0:
return K.exp(-d/10)-1
else:
return K.exp(d/13)-1


For the use of compiling my model:

model.compile(loss='mse', optimizer='adam', metrics=[score])

I received the following error code and I have not been able to correct the issue. Any help would be appreciated.

raise TypeError("Using a tf.Tensor as a Python bool is not allowed. " "Use if t is not None: instead of if t: to test if a " "tensor is defined, and use TensorFlow ops such as "

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

I'm assuming y_true and y_pred both are vectors. You are trying to apply a conditional on the value of a tensor. The library is telling you that it is not possible (tf.Tensor as Python bool).

You may want to check tensorflow control flow operations like tensorflow.equal

y_true and y_pred are both tensors in your code. Either change the code such that they're numpy arrays (I think this works) or look into tf.cond, which should allow you to do the operations you're looking for on tensors.

def _loss_tensor_score(y_true, y_pred):
y_error = y_pred - y_true
bool_idx = K.greater(y_error, 0)
loss1 = K.exp(-1*y_error/13) - 1 # greater 0
loss2 = K.exp(y_error/10) - 1    # less 0
loss = K.switch(bool_idx, loss2, loss1)
return K.sum(loss)


Maybe you can try this code.

What are you doing? Remaining useful life prediction?