Dataset object 消耗数据的三种方式
tensorflow ==2.2.0
for 逐个元素输出
因为Dataset object is a Python iterable.
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([8,3,0,8,2,1])
print(dataset)
for element in dataset:
print(element)
print(element.numpy())
shuchu
<TensorSliceDataset shapes: (), types: tf.int32>
tf.Tensor(8, shape=(), dtype=int32)
8
tf.Tensor(3, shape=(), dtype=int32)
3
tf.Tensor(0, shape=(), dtype=int32)
0
tf.Tensor(8, shape=(), dtype=int32)
8
tf.Tensor(2, shape=(), dtype=int32)
2
tf.Tensor(1, shape=(), dtype=int32)
1
从这里可以看出,element .numpy()就只是输出其相应的数字
创造一个Python iterator,用next 逐个消耗 **特别需要注意其用法
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([8,3,0,8,2,1])
it = iter(dataset)
print(next(it))
print(next(it).numpy())
输出
tf.Tensor(8, shape=(), dtype=int32) 从这里可以卡看出是一个一个地控制输出
3
使用reduce 一次性使用全部的元素
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([8,3,0,8,2,1])
print(dataset.reduce(0,lambda state, value: state+value).numpy())
注意
即使这次消耗完了,在后面的代码中也可以重新再读取 for reduce
但是对于next来说 ,分情况
情况一:next 没有消耗完所有的数据,可以再次另外接着在后文使用 for,reduce
情况二:
import tensorflow as tf
dataset = tf.data.Dataset.from_tensor_slices([8,3,0,8,2,1])
it = iter(dataset)
print(next(it).numpy()) #8
print(next(it).numpy()) #3
print(next(it).numpy()) #0
print(next(it).numpy()) #8
print(next(it).numpy()) #2
print(next(it).numpy()) #1
# print(next(it).numpy()) 如果next 的个数比element的个数还要多的话,就会程序报错