Creating custom conditional metric with Keras

老子叫甜甜 提交于 2020-07-08 13:50:48

问题


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

Custom Keras metric

where d=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.


回答1:


The metric you are providing is not a function that gets executed each time, but rather a construction of the function (computational graph) that needs to be evaluated. So it needs to be deterministic.

Try:

def score(y_true, y_pred):
    d = y_pred - y_true
    mask = K.less(y_pred, y_true)  # element-wise True where y_pred < y_pred
    mask = K.cast(mask, K.floatx())  # cast to 0.0 / 1.0
    s = mask * (K.exp(-d / 10) - 1) + (1 - mask) * (K.exp(d / 13) - 1)  
    # every i where mask[i] is 1, s[i] == (K.exp(-d / 10) - 1)
    # every i where mask[i] is 0, s[i] == (K.exp(d / 13) - 1)
    return s


来源:https://stackoverflow.com/questions/51902088/creating-custom-conditional-metric-with-keras

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!