简单来说:
from_tensors()
返回:一个元素,
类型:TensorDataset
from_tensor_slices()
返回:多个与输入长度相同的元素,
类型:TensorSliceDataset
解释:
from_tensors()
对于1-D输入
import tensorflow as tf
dataset_ft = tf.data.Dataset.from_tensors([1, 2, 3])
type(dataset_ft)
>>> tensorflow.python.data.ops.dataset_ops.TensorDataset
现在,如果我们循环遍历此数据集,我们只会得到一个对象:
for _ in dataset_ft:
print(_)
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int32)
如果我们提供2维或更多维的输入会怎样?
使用2维输入时
import tensorflow as tf
dataset_ft = tf.data.Dataset.from_tensors([[1, 2, 3], [4, 5, 6]])
type(dataset_ft)
>>> tensorflow.python.data.ops.dataset_ops.TensorDataset
现在,如果我们遍历这个数据集,我们仍然只会得到一个对象:
for _ in dataset_ft:
print(_)
>>> tf.Tensor(
>>> [[1 2 3]
>>> [4 5 6]], shape=(2, 3), dtype=int32)
正如您所看到的,生成的张量形状与输入相同,没有变化。
from_tensor_slices()
它删除第一维并将其用作数据集维度。
在使用1维输入时
import tensorflow as tf
dataset_fts = tf.data.Dataset.from_tensor_slices([1, 2, 3])
type(dataset_fts)
>>> tensorflow.python.data.ops.dataset_ops.TensorSliceDataset
现在,如果我们循环遍历这个数据集,我们将有多个对象:
for _ in dataset_fts:
print(_)
>>> tf.Tensor(1, shape=(), dtype=int32)
>>> tf.Tensor(2, shape=(), dtype=int32)
>>> tf.Tensor(3, shape=(), dtype=int32)
如果我们提供2维或更高维的输入,会发生什么?
使用2维输入
import tensorflow as tf
dataset_fts = tf.data.Dataset.from_tensor_slices([[1, 2, 3], [4, 5, 6]])
type(dataset_fts)
>>> tensorflow.python.data.ops.dataset_ops.TensorSliceDataset
如果我们循环遍历这个二维数据集,我们将得到两个一维元素。
for _ in dataset_fts:
print(_)
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int32)
>>> tf.Tensor([4 5 6], shape=(3,), dtype=int32)
这是我能给出的最简单的解释。为了更好地理解,建议您使用不同的输入运行这两个函数,并查看返回元素的形状。
from_tensors((t1, t2, t3,))
。有了这个知识,from_tensors
生成的数据集中,每个输入张量就像数据集的一行;而from_tensor_slices
生成的数据集中,每个输入张量就像数据集的一列。因此,在后一种情况下,所有张量的长度都必须相同,并且生成的数据集的元素(行)是由每列的一个元素组成的元组。 - user1488777