如何打印`tf.data.Dataset.from_tensor_slices`的结果?

guo*_*rui 8 tensorflow

我是tensorflow的新手,所以我在官方文档中尝试每一个命令.

如何正确打印结果dataset

这是一个例子: 在此输入图像描述

All*_*oie 17

默认情况下,TensorFlow会构建图形而不是立即执行操作.如果您想要文字值,请尝试tf.enable_eager_execution():

>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> X = tf.constant([[[1,2,3],[3,4,5]],[[3,4,5],[5,6,7]]])
>>> Y = tf.constant([[[11]],[[12]]])
>>> dataset = tf.data.Dataset.from_tensor_slices((X, Y))
>>> for x, y in dataset:
...   print(x, y)
... 
tf.Tensor(
[[1 2 3]
 [3 4 5]], shape=(2, 3), dtype=int32) tf.Tensor([[11]], shape=(1, 1), dtype=int32)
tf.Tensor(
[[3 4 5]
 [5 6 7]], shape=(2, 3), dtype=int32) tf.Tensor([[12]], shape=(1, 1), dtype=int32)
Run Code Online (Sandbox Code Playgroud)

在构建图形时,您需要创建tf.enable_eager_execution()并运行图形以获取文字值:

>>> import tensorflow as tf
>>> X = tf.constant([[[1,2,3],[3,4,5]],[[3,4,5],[5,6,7]]])
>>> Y = tf.constant([[[11]],[[12]]])
>>> dataset = tf.data.Dataset.from_tensor_slices((X, Y))
>>> tensor = dataset.make_one_shot_iterator().get_next()
>>> with tf.Session() as session:
...   print(session.run(tensor))
...
(array([[1, 2, 3],
       [3, 4, 5]], dtype=int32), array([[11]], dtype=int32))
Run Code Online (Sandbox Code Playgroud)