python - 属性错误: 'Tensor' object has no attribute 'numpy' in Tensorflow 2. 1

标签 python numpy tensorflow tfrecord tensorflow2.x

我正在尝试转换 shape Tensor 的属性在 Tensorflow 2.1 中,我收到此错误:

AttributeError: 'Tensor' object has no attribute 'numpy'

我已经检查了 tf.executing eagerly() 的输出是 True ,

一些上下文:我加载了 tf.data.Dataset来自 TFRecords,然后我应用 map 。映射函数正在尝试转换 shape数据集样本之一的属性 Tensor到 numpy:

def _parse_and_decode(serialized_example):
    """ parse and decode each image """
    features = tf.io.parse_single_example(
        serialized_example,
        features={
            'encoded_image': tf.io.FixedLenFeature([], tf.string),
            'kp_flat': tf.io.VarLenFeature(tf.int64),
            'kp_shape': tf.io.FixedLenFeature([3], tf.int64),
        }
    )
    image = tf.io.decode_png(features['encoded_image'], dtype=tf.uint8)
    image = tf.cast(image, tf.float32)

    kp_shape = features['kp_shape']

    kp_flat = tf.sparse.to_dense(features['kp_flat'])
    kp = tf.reshape(kp_flat, kp_shape)

    return image, kp


def read_tfrecords(records_dir, batch_size=1):
    # Read dataset from tfrecords
    tfrecords_files = glob.glob(os.path.join(records_dir, '*'))
    dataset = tf.data.TFRecordDataset(tfrecords_files)
    dataset = dataset.map(_parse_and_decode, num_parallel_calls=batch_size)
    return dataset


def transform(img, labels):
    img_shape = img.shape  # type: <class 'tensorflow.python.framework.ops.Tensor'>`
    img_shape = img_shape.numpy()  # <-- Throws the error
    # ...    

dataset = read_tfrecords(records_dir)

这会引发错误:

dataset.map(transform, num_parallel_calls=1)

虽然这完全有效:

for img, labels in dataset.take(1):
    print(img.shape.numpy())

编辑:尝试访问 img.numpy()而不是img.shape.numpy()在上面的变压器和代码中会产生相同的行为。

我检查了 img_shape 的类型它是<class 'tensorflow.python.framework.ops.Tensor'> .

有人在新版本的 Tensorflow 中解决了此类问题吗?

最佳答案

代码中的问题是您无法在映射到 tf.data.Datasets 的函数内部使用 .numpy(),因为 .numpy( ) 是 Python 代码,而不是纯 TensorFlow 代码。

当您使用 my_dataset.map(my_function) 等函数时,您只能在 my_function 函数中使用 tf.* 函数。

这不是 TensorFlow 2.x 版本的错误,而是出于性能目的在幕后如何生成静态图的错误。

如果您想在映射到数据集的函数内使用自定义 Python 代码,则必须使用 tf.py_function(),文档:https://www.tensorflow.org/api_docs/python/tf/py_function 。在数据集上映射时,确实没有其他方法可以混合 Python 代码和 TensorFlow 代码。

您还可以咨询此问题以获取更多信息;这正是我几个月前问过的问题:Is there an alternative to tf.py_function() for custom Python code?

关于python - 属性错误: 'Tensor' object has no attribute 'numpy' in Tensorflow 2. 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60347349/

相关文章:

tensorflow - tensorflow 中 RNN 和 Seq2Seq 模型的 API 引用

tensorflow - Dense(2)和Dense(1)之间的区别是二进制分类CNN的最后一层?

python - 如何在 Python 中为需要文件名的函数提供 URL

python - 使用 alexnet 和 flow from 目录来训练灰度数据集

python - 从 selectKbest 获取特征名称

python - .std() & .skew() 用 .rolling 给出错误答案

python - 查找二维 numpy 数组中最大和的位置

python - Tensorflow GPU 利用率低于 10%

python - Pandas Dataframe 或 Panel 到 3d numpy 数组

python - 将结果写入 Python 中的参数?