tensorflow==2.2.0
一维列表
import tensorflow as tf
## for 1D tensor produce **scalar tensor elements**
dataset = tf.data.Dataset.from_tensor_slices([1,2,3])
print(type(dataset))
for element in dataset:
print(element)
输出
<class 'tensorflow.python.data.ops.dataset_ops.TensorSliceDataset'>
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor(3, shape=(), dtype=int32)
二维列表
# slicing a 2D tensor produces 1D tensor elements
import tensorflow as tf
two = [[1,2],[3,4]]
print(two)
print(type(two))
dataset2 = tf.data.Dataset.from_tensor_slices(two)
print(dataset2.as_numpy_iterator()) # method1
print(list(dataset2.as_numpy_iterator())) # method2
for element in dataset2: # method3
print(element)
输出
[[1, 2], [3, 4]]
<class 'list'>
<tensorflow.python.data.ops.dataset_ops._NumpyIterator object at 0x00000000117A56C8>
[array([1, 2]), array([3, 4])]
tf.Tensor([1 2], shape=(2,), dtype=int32)
tf.Tensor([3 4], shape=(2,), dtype=int32)
所以,这里可以看到:
**1.使用as_numpy_iterator可以看到你的数据集的内容。即print(dataset2.as_numpy_iterator())
指南中这样写道:
as_numpy_iterator() -----returns an iterator which converts all elements of dataset to numpy.
2.如果想要直接查看元素的shapes 还有types ,就要用
for element in dataset::
print(element) **
元组
# Slicing a tuple of 1D tensor produces tuple elements containing scalar tensors.
three = ([1,2],[3,4],[5,6],[7,8])
print(three)
print(type(three))
dataset3 = tf.data.Dataset.from_tensor_slices(three)
print(list(dataset3.as_numpy_iterator()))# method2
for element in dataset3:
print(element)
输出
([1, 2], [3, 4], [5, 6], [7, 8])
<class 'tuple'>
[(1, 3, 5, 7), (2, 4, 6, 8)]
(<tf.Tensor: shape=(), dtype=int32, numpy=1>, <tf.Tensor: shape=(), dtype=int32, numpy=3>, <tf.Tensor: shape=(), dtype=int32, numpy=5>, <tf.Tensor: shape=(), dtype=int32, numpy=7>)
(<tf.Tensor: shape=(), dtype=int32, numpy=2>, <tf.Tensor: shape=(), dtype=int32, numpy=4>, <tf.Tensor: shape=(), dtype=int32, numpy=6>, <tf.Tensor: shape=(), dtype=int32, numpy=8>)
看每个元素还是元组
字典
# for dictionary
four = {"a":[1,2],"b":[3,4],"c":[5,6]}
print(four)
print(type(four))
dataset4 = tf.data.Dataset.from_tensor_slices(four)
print(list(dataset4.as_numpy_iterator()))# method2
for element in dataset4:
print(element)
输出
{'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}
<class 'dict'>
[{'a': 1, 'b': 3, 'c': 5}, {'a': 2, 'b': 4, 'c': 6}]
{'a': <tf.Tensor: shape=(), dtype=int32, numpy=1>, 'b': <tf.Tensor: shape=(), dtype=int32, numpy=3>, 'c': <tf.Tensor: shape=(), dtype=int32, numpy=5>}
{'a': <tf.Tensor: shape=(), dtype=int32, numpy=2>, 'b': <tf.Tensor: shape=(), dtype=int32, numpy=4>, 'c': <tf.Tensor: shape=(), dtype=int32, numpy=6>}
看每个元素还是字典