【问题标题】:Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution - when I do not use it as a bool在图形执行中不允许使用 `tf.Tensor` 作为 Python `bool` - 当我不将其用作 bool 时
【发布时间】:2020-10-21 19:59:09
【问题描述】:

这就是我遇到的问题,但我不会在任何地方将它用作布尔值。或者至少不是我能找到的地方。我读过类似的问题,它们已得到解决,因为实际上有一个实例将其视为布尔值。但是,我没有使用它作为布尔值。

功能:

def compile_cnn(model, loss = None, optimizer = None):

    # Compile the CNN using the specified loss function
    model.compile(loss=loss, optimizer=optimizer)

    # return the compiled model
    return model

自定义 Keras 损失函数:

def contrastive_loss(label, embedding, margin = 0.4):

    # Assign the label
    y = label

    # Assign the embeddings
    p1 = embedding[0]
    p2 = embedding[1]

    # Get the euclean distance    
    d = tf.norm(p1 - p2, axis=-1)

    if y == 0:
        return (1/2) * math.sqrt(d)
    else:
        return (1/2) * math.sqrt(max(0, (margin-d)))

调用代码:

# We use Adam as optimizer
optimizer = keras.optimizers.Adam() 

# Compile the model with the contrastive loss function
cont_loss_model = compile_cnn(model, contrastive_loss, optimizer)

这是所要求的完整错误消息。

 C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:806 train_function  *
        return step_function(self, iterator)
    C:\Users\User\Documents\Uni\2020\IFN680\Assignment 2\SiameseNetwork.py:88 contrastive_loss  *
        return (1/2) * tf.math.sqrt(max(0, (margin-d)))
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:877 __bool__  **
        self._disallow_bool_casting()
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:486 _disallow_bool_casting
        self._disallow_when_autograph_enabled(
    C:\Users\User\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:472 _disallow_when_autograph_enabled
        raise errors.OperatorNotAllowedInGraphError(

    OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

enter code here

在此处输入代码

【问题讨论】:

  • 请显示错误信息的完整回溯。它可能准确地解释了为什么该值被用作布尔值,即使您不希望您的代码具有这种效果。事实上,我们甚至无法判断程序中的哪个东西是它所抱怨的张量。

标签: python tensorflow keras


【解决方案1】:

通过在自定义损失函数中添加@tf.function 解决了这个问题:

@tf.function
def contrastive_loss(label, embedding, margin = 0.4):

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2018-07-12
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多