我想定义自定义丢失,但似乎无法将keras张量date_range
与单值K.sum(y_true)
进行比较。
0
我还尝试了def custom_loss_keras(y_true, y_pred):
if(K.sum(y_true) > 0):
loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
return loss
else:
loss = 0.0
return loss
内部丢失函数来获取numpy数组,但它失败了。
K.eval()
更新
def custom_loss_keras(y_true, y_pred):
y_true_np = K.eval(y_true)
#if(K.sum(y_true) > 0):
if(np.sum(y_true_np) > 0):
loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
return loss
else:
loss = 0.0
return loss
它产生错误:
def custom_loss_keras(y_true, y_pred):
if(K.greater(K.sum(y_true), 0)):
loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
return loss
else:
loss = 0.0
return loss
此外,我还尝试将建议的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.
与keras函数结合使用:
tf.cond
它产生错误:
def custom_loss_keras(y_true, y_pred):
loss = tf.cond(K.greater(K.sum(y_true),0), K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1), 0.0)
return loss
好像我需要用纯张量流写它?
答案 0 :(得分:2)
在损失函数中使用if
和else
(或K.eval
)将无效,因为custom_loss_keras
中的行是在模型编译期间执行的,而不是模型拟合。
您可以使用tf.cond
:
K.switch
def custom_loss_keras(y_true, y_pred):
loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
condition = K.greater(K.sum(y_true), 0)
return K.switch(condition, loss, K.zeros_like(loss))
答案 1 :(得分:1)
Keras后端无法理解>作为运算符,您必须使用内置的Keras逻辑运算符大于:
K.greater(x, y)
在你的情况下:
x = K.sum(y_true)
y = 0