【问题标题】:How to print the result of `tf.data.Dataset.from_tensor_slices`?如何打印`tf.data.Dataset.from_tensor_slices`的结果?
【发布时间】:2018-09-26 04:01:36
【问题描述】:

我是 tensorflow 的新手,所以我尝试了官方文档中出现的每一个命令。

如何正确打印结果dataset?这是我的例子:

import tensorflow as tf
import numpy as np
sess = tf.Session()
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))

dataset
print type(dataset)
# print help(dataset)
# print dataset.output_classes
# print dataset.output_shapes

【问题讨论】:

  • print(dataset) 呢?
  • print(dataset)<BatchDataset shapes: ((?, 2, 3), (?, 1, 1)), types: (tf.int32, tf.int32)>
  • 你会期待什么?
  • 我的预期输出类似于[[1,2,3],[3,4,5]],[11][[3,4,5],[5,6,7]],[12],即特征与其标签配对。
  • 您可以使用list(dataset.as_numpy_iterator())。对于测试,您也可以使用for x in dataset.take(10).as_numpy_iterator(): print(x)

标签: tensorflow


【解决方案1】:

默认情况下,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)

请注意,在 TensorFlow 2.x 中,tf.enable_eager_execution() 是默认行为,符号不存在;你可以把那条线去掉。

在 TensorFlow 1.x 中构建图形时,您需要创建 Session 并运行图形以获取字面值:

>>> 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))

【讨论】:

  • 太好了,这就是我想要的。非常感谢!
  • 谢谢!请注意 make_one_shot_iterator() 现在已弃用;我们不再需要迭代器了。解决方法是简单地写: for x,y in dataset: print(x,y)
  • 好点,我已经从急切执行示例中删除了 make_one_shot_iterator。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 2021-12-13
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2016-11-22
相关资源
最近更新 更多