How to print one example of a dataset from tf.data?

Question:

I have a dataset in tf.data. How can I easily print (or grab) one element in my dataset?

Similar to:

print(dataset[0])
Asked By: Nicky Feller

||

Answers:

In TF 1.x you can use the following. There are different iterators provided (some might be deprecated in future versions).

import tensorflow as tf

d = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4])
diter = d.make_one_shot_iterator()
e1 = diter.get_next()

with tf.Session() as sess:
  print(sess.run(e1))

Or in TF 2.x

import tensorflow as tf

d = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4])
print(next(iter(d)).numpy())

## You can also use loops as follows to traverse the full set one item at a time
for elem in d:
    print(elem)

Answered By: thushv89

If your TensorFlow dataset is named dataset, you can access the first element like this:

list(dataset.as_numpy_iterator())[0]

See documentation.

Answered By: J. V.

You can also combine the as_numpy_iterator method, proposed by J.V. with the take method that allows you to specify how many elements you want to extract from tf dataset. For example:

import tensorflow as tf

>>> dataset = tf.data.Dataset.range(10)
>>> dataset = dataset.take(1) # take one element (the first)
>>> list(dataset.as_numpy_iterator())
0

Changing the number in the take method will allow you to extract a different number of elements (in the order they were inserted in the dataset).

Answered By: Aelius