Aal*_*k_G 9 python numpy tensorflow tensorflow-datasets
我正在使用 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))
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常并输出[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)
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了以下错误 AttributeError: 'Tensor' object has no attribute 'numpy'
我无法弄清楚为什么 tensor.numpy() 在 tf.data.Dataset.map() 的情况下不起作用
编辑
以下段落阐明了我的目的:
我有一个数据集文件夹,其中包含数百万个数据对(图像、时间序列)。整个数据集不适合内存,所以我使用 tf.data.Dataset.map(func)。在 func() 函数中,我想加载一个包含时间序列的 numpy 文件并加载图像。为了加载图像,tensorflow 中有内置函数,如 tf.io.read_file 和 tf.image.decode_jpeg 接受字符串张量。但是 np.load() 不接受字符串张量。这就是我想将字符串张量转换为标准 python 字符串的原因。
从 .map()文档:
无论定义 map_func 的上下文如何(eager vs. graph),tf.data 都会跟踪函数并将其作为图形执行。
要在内部使用 Python 代码,.map()您有两个选择:
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" ]
Run Code Online (Sandbox Code Playgroud)
我希望这仍然有用。
不同之处在于,第一个示例是急切执行的,但tf.data.Dataset本质上是延迟评估的(有充分的理由)。
数据集可用于表示任意大(甚至无限)的数据集,因此它们仅在计算图中进行评估,以使数据能够以块的形式传递。
这意味着诸如此类的急切执行方法numpy()在数据集管道中不可用。
| 归档时间: |
|
| 查看次数: |
5722 次 |
| 最近记录: |