python - Keras:如何将自定义损失中的 K.sum(y_true) 与 0 进行比较?

标签 python deep-learning keras

我想定义自定义损失,但似乎无法将 keras 张量 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

我还在损失函数中尝试了 K.eval() 来获取 numpy 数组,但失败了。

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.

我还尝试将建议的 tf.cond 与 keras 函数结合起来:

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

它产生错误:

     22 def custom_loss_keras(y_true, y_pred):
---> 23     loss = tf.cond(K.greater(K.sum(y_true),0), K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1), 0.0)
     24 
     25     return loss

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/control_flow_ops.py in cond(pred, fn1, fn2, name)
   1718   with ops.name_scope(name, "cond", [pred]) as name:
   1719     if not callable(fn1):
-> 1720       raise TypeError("fn1 must be callable.")
   1721     if not callable(fn2):
   1722       raise TypeError("fn2 must be callable.")

TypeError: fn1 must be callable.

看来我需要用纯 tensorflow 来编写它?

最佳答案

在损失函数中使用 ifelse(或 K.eval)将不起作用,因为 custom_loss_keras 中的行 在模型编译期间执行,而不是模型拟合期间执行。

您可以使用K.switch,而不是调用tf.cond:

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))

关于python - Keras:如何将自定义损失中的 K.sum(y_true) 与 0 进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533965/

相关文章:

deep-learning - 如何开始为我的图层编写代码?

python - 通过多次前向传播进行反向传播

python - 使用 odo 将巨大的 h5 文件与多个数据集合并为一个

python - 有没有办法通过猴子修补向类 __init__ 方法添加参数?

machine-learning - 使用caffe从图像回归年龄时如何设计损失层

networking - Keras神经网络: saving weights with checkpoints or with save_weights?

python - 塑造 LSTM 的数据,并将密集层的输出馈送到 LSTM

python Flask SQLAlchemy 将数据插入 mysql

我的 reduce getattr 问题的 Pythonic 解决方案

python - 属性错误 : 'Model' object has no attribute 'name'