Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the result of `tf.data.Dataset.from_tensor_slices`?

Tags:

tensorflow

I'm a new to tensorflow, so I try every single command appeared in the official document.

How can I properly print the result dataset? Here is my example:

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
like image 235
guorui Avatar asked Apr 16 '18 12:04

guorui


1 Answers

By default TensorFlow builds up a graph rather than executing operations immediately. If you'd like literal values, try 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)

Note that in TensorFlow 2.x tf.enable_eager_execution() is the default behavior and the symbol doesn't exist; you can just take that line out.

When graph building in TensorFlow 1.x, you need to create a Session and run the graph to get literal values:

>>> 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))
like image 174
Allen Lavoie Avatar answered Oct 26 '22 06:10

Allen Lavoie