keras 在Graph执行中不允许将'tf.Tensor'用作Python的'bool'-当我不将其用作bool时

c8ib6hqw  于 2022-11-13  发布在  Python
关注(0)|答案(1)|浏览(196)

这就是我遇到的问题,但我没有把它当作布尔值使用。或者至少我没有看到。我读过类似的问题,它们被解决了,因为事实上有一个示例,它被当作布尔值处理。但是,我没有把它当作布尔值使用。
功能:

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.
brgchamk

brgchamk1#

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

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

相关问题