tf.data.Dataset.from_tensor_slices()

函数原型:

tf.data.Dataset.from_tensor_slices(tensors)

作用是对传入的tensor在第一个维度进行切分,生成相应的dataset

实例一

import tensorflow as tf
import numpy as np
x = np.random.uniform(size=(5, 2))
print(x)
dataset = tf.data.Dataset.from_tensor_slices(x)
for ele in dataset:
	print(ele)

输出结果:

[[0.12831178 0.79162472]
 [0.35773058 0.47912444]
 [0.82993602 0.27870491]
 [0.77596611 0.2247823 ]
 [0.74720115 0.44322264]]

tf.Tensor([0.12831178 0.79162472], shape=(2,), dtype=float64)
tf.Tensor([0.35773058 0.47912444], shape=(2,), dtype=float64)
tf.Tensor([0.82993602 0.27870491], shape=(2,), dtype=float64)
tf.Tensor([0.77596611 0.2247823 ], shape=(2,), dtype=float64)
tf.Tensor([0.74720115 0.44322264], shape=(2,), dtype=float64)

可以看到ndarray 类型的x被在第0维切分成了5个不同tensor

实例二

import tensorflow as tf
import numpy as np
x = np.random.uniform(size=(5, 2))
print(x)
y = np.random.uniform(size=(5,))
print(y)
dataset = tf.data.Dataset.from_tensor_slices((x, y))
for ele in dataset:
	print(ele)
dataset

输出结果:

[[0.12831178 0.79162472]
 [0.35773058 0.47912444]
 [0.82993602 0.27870491]
 [0.77596611 0.2247823 ]
 [0.74720115 0.44322264]]

[0.80429699 0.66643469 0.43370019 0.68620174 0.62197102]

(, )
(, )
(, )
(, )
(, )


xy均在第0维被切分成了5个tensor,并且相应位置的元素在dataset中组成了一组。

实例三:使用字典+tf.data.Dataset.slices()创建dataset

import tensorflow as tf
import numpy as np
dict_data = dict([('a', [1,2]), ('b', [3, 4]), ('c', [5, 6])])
dict_data
dataset = tf.data.Dataset.from_tensor_slices(dict_data)
for ele in dataset:
	print(ele)
dataset

输出结果:

{'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}

{'a': , 'b': , 'c': }
{'a': , 'b': , 'c': }


这里我也不太明白为什么是这样一个结果?

打印使用tf.data.Dataset.from_tensor_slices()生成的dataset的方法

使用for循环
for ele in dataset:
	print(ele)
使用dataset.take,打印固定个数的元素
for ele in dataset.take(5):
	print(ele)
打印dataset中的下一个元素
next(iter(dataset.take(1)))

你可能感兴趣的:(笔记,tensorflow)