【问题标题】:tensor.numpy() not working in tensorflow.data.Dataset. Throws the error: AttributeError: 'Tensor' object has no attribute 'numpy'tensor.numpy() 在 tensorflow.data.Dataset 中不起作用。引发错误:AttributeError: 'Tensor' object has no attribute 'numpy'
【发布时间】:2019-11-02 02:05:35
【问题描述】:

我正在使用 tensorflow 2.0.0-beta1 和 python 3.7

首先考虑以下 tensor.numpy() 正常工作的代码:

import tensorflow as tf
import numpy as np

np.save('data.npy',np.ones(1024))

def func(mystr): 
    return np.load(mystr.numpy())

mystring = tf.constant('data.npy')
print(func(mystring))

以上代码运行正常,输出[1. 1. 1. ... 1. 1. 1.]

现在考虑以下代码,其中 tensor.numpy() 不起作用。

import tensorflow as tf
import numpy as np

np.save('data.npy',np.ones(1024))

def func(mystr):
    return np.load(mystr.numpy())

mystring = tf.constant('data.npy')
data = tf.data.Dataset.from_tensor_slices([mystring])
data.map(func,1)

上面的代码给出了以下错误AttributeError: 'Tensor' object has no attribute 'numpy'

我无法弄清楚为什么 tensor.numpy() 在 tf.data.Dataset.map() 的情况下不起作用

编辑

以下段落阐明了我的目的:

我有一个包含数百万数据对(图像、时间序列)的数据集文件夹。整个数据集不适合内存,所以我使用 tf.data.Dataset.map(func)。在 func() 函数中,我想加载一个包含时间序列的 numpy 文件以及加载图像。为了加载图像,张量流中有内置函数,例如 tf.io.read_file 和 tf.image.decode_jpeg 接受字符串张量。但是 np.load() 不接受字符串张量。这就是为什么我想将字符串张量转换为标准的 python 字符串。

【问题讨论】:

  • 你为什么在 func 中使用 numpy ?你想达到什么目的?
  • 我已经稍微编辑了我的问题以明确我的目的。我有一个数据集文件夹,其中包含数百万个数据对(图像、时间序列)。整个数据集不适合内存,所以我使用 tf.data.Dataset.map(func)。在 func() 函数中,我想加载一个包含时间序列的 numpy 文件以及加载图像。为了加载图像,张量流中有内置函数,如 tf.io.read_filetf.image.decode_jpeg 接受字符串张量。但是 np.load() 不接受字符串张量。这就是为什么我想将字符串张量转换为标准的 python 字符串。

标签: python numpy tensorflow tensorflow-datasets


【解决方案1】:

来自 .map() documentation:

无论定义 map_func 的上下文如何(eager vs. graph),tf.data 都会跟踪函数并将其作为图执行。

要在.map() 中使用 Python 代码,您有两种选择:

  1. 依靠 AutoGraph 将 Python 代码转换为等效的图形计算。这种方法的缺点是 AutoGraph 可以转换部分但不是全部 Python 代码。
  2. 使用tf.py_function,它允许您编写任意 Python 代码,但通常会导致性能比 1) 差。

例如:

d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])

#  transform a byte string tensor to a byte numpy string and decode to python str
#  upper case string using a Python function
def upper_case_fn(t):
    return t.numpy().decode('utf-8').upper()

#  use the python code in graph mode
d.map(lambda x: tf.py_function(func=upper_case_fn,
      inp=[x], Tout=tf.string))  # ==> [ "HELLO", "WORLD" ]

我希望这仍然有用。

【讨论】:

  • 更多关于 tf.py_function 的例子可以在官方文档(tf.data:构建 TensorFlow 输入管道)的“应用任意 Python 逻辑”一节中找到
【解决方案2】:

不同之处在于第一个示例是急切执行的,但 tf.data.Dataset 本质上是惰性求值的(有充分的理由)。

数据集可用于表示任意大(甚至无限)的数据集,因此它们仅在计算图中进行评估,以使数据能够以块的形式传递。

这意味着诸如numpy() 等急切执行的方法在数据集管道中不可用。

【讨论】:

  • 非常感谢您的回复。如果 .numpy() 不可用,那么如何将字符串张量转换为普通字符串,以便可以使用 np.load(mystr)
  • 第二!如果我不能使用 .numpy()/.eval() 那么如何将数据从我的张量中取出到一个 numpy 数组中?
猜你喜欢
  • 2020-11-21
  • 2018-12-01
  • 1970-01-01
  • 2022-12-01
  • 2022-12-03
  • 2023-01-02
  • 2021-08-09
  • 2014-12-20
  • 2021-11-08
相关资源
最近更新 更多