import numpy as np
import tensorflow as tf
tf.__version__
# '2.2.0-rc2'
np.version.version
# '1.18.2'
dataset1 = tf.data.Dataset.from_tensor_slices([1, 2, 3])
for element in dataset1:
print(element)
print(type(element.numpy()))
我们得到结果
tf.Tensor(1, shape=(), dtype=int32) <class 'numpy.int32'> tf.Tensor(2, shape=(), dtype=int32) <class 'numpy.int32'> tf.Tensor(3, shape=(), dtype=int32) <class 'numpy.int32'>
如所料,所有数据类型均为int32
。但是更改此简单示例以提供字符串列表而不是整数:
dataset2 = tf.data.Dataset.from_tensor_slices(['1', '2', '3']) for element in dataset2: print(element) print(type(element.numpy()))
给出结果
tf.Tensor(b'1', shape=(), dtype=string) <class 'bytes'> tf.Tensor(b'2', shape=(), dtype=string) <class 'bytes'> tf.Tensor(b'3', shape=(), dtype=string) <class 'bytes'>
令人惊讶的是,尽管张量本身为dtype=string
,但它们的求值为bytes
类型。此行为不限于
.from_tensor_slices
方法;这是.list_files
的情况(以下代码段在新的Colab笔记本中直接运行):
.list_files
结果为:
disc_data = tf.data.Dataset.list_files('sample_data/*.csv') # 4 csv files for element in disc_data: print(element) print(type(element.numpy()))
再一次,尽管张量本身是tf.Tensor(b'sample_data/california_housing_test.csv', shape=(), dtype=string) <class 'bytes'> tf.Tensor(b'sample_data/mnist_train_small.csv', shape=(), dtype=string) <class 'bytes'> tf.Tensor(b'sample_data/california_housing_train.csv', shape=(), dtype=string) <class 'bytes'> tf.Tensor(b'sample_data/mnist_test.csv', shape=(), dtype=string) <class 'bytes'>
,但评估的张量中的文件名将以bytes
而不是string
的形式返回。
dtype=string
方法也观察到类似的行为(此处未显示)。>>[最终演示:如
.from_generator
方法.as_numpy_iterator
中所示,以下相等条件被评估为documentation:
True
但是如果我们将dataset3 = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]), 'b': [5, 6]}) list(dataset3.as_numpy_iterator()) == [{'a': (1, 3), 'b': 5}, {'a': (2, 4), 'b': 6}] # True
的元素更改为字符串,则相等条件现在令人惊讶地评估为b
!
False
[可能由于数据类型不同,因为值本身显然相同。
我没有通过学术实验偶然发现这种行为;我正在尝试使用自定义函数将数据传递给TF数据集,这些函数从表格的磁盘中读取文件对。
dataset4 = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]), 'b': ['5', '6']}) # change elements of b to strings list(dataset4.as_numpy_iterator()) == [{'a': (1, 3), 'b': '5'}, # here {'a': (2, 4), 'b': '6'}] # also # False
哪些自定义函数本身可以很好地运行,但是可以通过TF数据集进行映射
f = ['filename1', 'filename2']
在此挖掘之后,如果返回的数据类型确实为RuntimeError: not a string
而不是bytes
,则似乎至少无法解释。所以,这是一个错误(看起来),还是我在这里遗漏了什么?
下面的所有可复制代码都是在TF 2.2.0-rc2的Google Colab上运行的。修改文档中的简单示例以从简单的Python列表创建数据集:将numpy导入为np import ...
发件人:string