使用Keras创建自定义条件指标 [英] Creating custom conditional metric with Keras
问题描述
我正在尝试使用keras为我的神经网络创建以下指标:
I am trying to create the following metric for my neural network using keras:
其中d = y_ {pred} -y_ {true}
where d=y_{pred}-y_{true}
y_ {pred}和y_ {true}都是向量
and both y_{pred} and y_{true} are vectors
使用以下代码:
将keras.backend导入为K
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
用于编译我的模型:
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(使用
tf.Tensor
作为Pythonbool
不是 允许的. "使用if t is not None:
而不是if t:
来测试是否 定义了张量,并使用TensorFlow操作,例如"
raise TypeError("Using a
tf.Tensor
as a Pythonbool
is not allowed. " "Useif t is not None:
instead ofif t:
to test if a " "tensor is defined, and use TensorFlow ops such as "
TypeError:不允许将tf.Tensor
用作Python bool
.使用
if t is not None:
而不是if t:
来测试是否定义了张量,
并使用诸如tf.cond之类的TensorFlow操作来执行子图
以张量的值为条件.
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.
推荐答案
您提供的指标不是每次都会执行的函数,而是需要评估的函数(计算图)的构造.因此,它必须是确定性的.
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.
尝试:
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
这篇关于使用Keras创建自定义条件指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!