Tensorflow 2 - OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function

Tensorflow 2 - OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function

我正在为 Tensorflow 2 中的数据集编写映射函数。 数据集包含几个图像和相应的标签,更具体地说,标签只有三个可能的值,13、17 和 34。 映射函数应该获取标签并将它们转换为分类标签。

可能有更好的方法来实现这个功能(欢迎提出建议),但这是我的实现:

def map_labels(dataset):

    def convert_labels_to_categorical(image, labels):
        labels = [1.0, 0., 0.] if labels == 13 else [0., 1.0, 0.] if labels == 17 else [0., 0., 1.0]

        return image, labels

        categorical_dataset = dataset.map(convert_labels_to_categorical)

    return categorical_dataset

主要问题是我收到以下错误:

OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.

我真的不知道这个错误是什么意思,互联网上也没有那么多其他来源记录同样的错误。有什么想法吗?

编辑(新的非工作实施):

def map_labels(dataset):

    def convert_labels_to_categorical(image, labels):
        labels = tf.Variable([1.0, 0., 0.]) if tf.reduce_any(tf.math.equal(labels, tf.constant(0,dtype=tf.int64))) \
        else tf.Variable([0., 1.0, 0.]) if tf.reduce_any(tf.math.equal(labels, tf.constant(90,dtype=tf.int64))) \
        else tf.Variable([0., 0., 1.0])

        return image, labels

    categorical_dataset = dataset.map(convert_labels_to_categorical)

    return categorical_dataset

您的问题来自于您将 Python 代码与 TensorFlow 代码混合在一起。

实际上,在您的 map 函数中您使用任意 Python 代码,而不是专门优化的 TensorFlow 代码

map 函数中,您只能使用属于 tf* 类别的函数。如果您仍想使用任意 Python 代码,则需要使用 tf.py_function() 库。

您可能需要查阅此线程以获得更好的概述:

要解决您的问题,您需要专门使用tf模块中的函数,例如tf.stringstf.bool

我找到了可行的解决方案。首先,我创建了一个字典,然后是数据集:

dictionary = {"data":data, "labels":labels.astype('int32')}
dataset = tf.data.Dataset.from_tensor_slices(dict(dictionary))

这让我可以轻松访问数据集内的数据和标签。可能还有其他不需要使用字典的方法,但这个对我有用。对于我使用的映射:

def map_labels(dataset):

    def convert_labels_to_categorical(dataset):
        if dataset['labels'] ==  tf.constant(13):
            dataset['labels'] = tf.constant([1, 0, 0]) 

        elif dataset['labels'] == tf.constant(17):
            dataset['labels'] =  tf.constant([0, 1, 0])

        elif dataset['labels'] == tf.constant(34):
            dataset['labels'] = tf.constant([0, 0, 1])

        return dataset

    categorical_dataset = dataset.map(convert_labels_to_categorical)

    return categorical_dataset

映射数据集后,如果我用 categorical_dataset.element_spec 检查它,我得到:

{'data': TensorSpec(shape=(32, 32, 3), dtype=tf.uint8, name=None), 'labels': TensorSpec(shape=(None,), dtype=tf.int32, name=None)}

如果我打印元素,新的分类标签会正确分配给相应的图像。 综上所述,=== 仍然对 tf 变量起作用。