【问题标题】:Where is the 'TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed' coming from?'TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed' 来自哪里?
【发布时间】:2019-10-01 19:32:50
【问题描述】:

我正在定义以下损失函数:

smooth = 1.0
def loss(y_true, y_pred):
    y_true_f = K.flatten(y_true)
    y_pred_f = K.flatten(y_pred)
    if K.sum(y_true_f) == 0 and K.sum(y_pred_f) == 0:
        return 1
    else:
        intersection = K.sum(y_true_f * y_pred_f)
        return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)

这可行,但是当我将第 4 行更改为 if K.sum(y_true) > 0 and K.sum(y_pred) > 0: 时,我得到了问题标题中提到的 TypeError。

谁能告诉我这是怎么回事?谢谢。

【问题讨论】:

    标签: python tensorflow keras loss-function


    【解决方案1】:

    没错,tensorflow 的工作原理是首先编译所有将要完成的操作的图表。这类似于 Java 和 C++ 必须先编译代码,然后分别运行。因此,您不能在 tensorflow 代码中使用 python if 语句,因为在编译时实际上没有任何数字,因此它不知道要遵循哪条路线。

    为了解决这个问题,您需要编写没有任何 python if 语句的代码。这通常说起来容易做起来难,但幸运的是,在您使用tf.where 调用的情况下,它看起来非常简单。我的代码示例在 tensorflow 中,因为这是我所知道的,但希望将其扩展到 keras 应该很容易。

    total = tf.abs(tf.reduce_sum(y_true_f)) + tf.abs(tf.reduce_sum(y_pred_f))
    divisor = tf.where(tf.equal(total, 0), 1, total)
    # Now we can divide cleanly
    return (2. * intersection + smooth) / (divisor + smooth)
    

    【讨论】:

    • 我明白了!但是当 K.sum(y_true_f) == 0 和 K.sum(y_pred_f) == 0 时,这不会返回 1!它只是将除数设置为 1。还是我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 2020-11-08
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多