4

I have a data generator that I am producing training images from. I'd like to feed the data into the Tensorflow model by using this Python data generator, but I can't figure out how to convert the generator to a Tensorflow tensor. I'm looking for something similar to Keras' fit_generator() function.

Thanks!

1
  • 1
    what specifically is there error? and what have you tried. fit_generator take a generator as argument, why would you need anything else? Commented Dec 22, 2017 at 22:07

1 Answer 1

10

The tf.data.Dataset.from_generator() method provides a way to convert Python generators into tf.Tensor objects that evaluate to each successive element from the generator.

Let's say you have a simple generator that generates tuples (but could alternatively generate lists or NumPy arrays):

def g():
  yield 1, 10.0, "foo"
  yield 2, 20.0, "bar"
  yield 3, 30.0, "baz"

You can use the tf.data API to convert the generator first to a tf.data.Dataset, then to a tf.data.Iterator, and finally to a tuple of tf.Tensor objects.

dataset = tf.data.Dataset.from_generator(g, (tf.int32, tf.float32, tf.string))

iterator = dataset.make_one_shot_iterator()

int_tensor, float_tensor, str_tensor = iterator.get_next()

You can then use int_tensor, float_tensor, and str_tensor as the inputs to your TensorFlow model. See the tf.data programmer's guide for more ideas.

Sign up to request clarification or add additional context in comments.

4 Comments

What would be the tf type corresponding to image data (imageio.core.util.Image) of a component from the generator's yield (next)? Is there such tf.image?
Hi, @mrry, im wondering that whether can i use tf.data.Dataset.from_generator to with python generator that will yield (single image),(python_list)?
This is TF1 code, which requires tf.compat.v1.data.Dataset.from_generator to run in TF2. I'm sure TF2 has some better solution, but that's what I'm using so far
Actually, it seems the TensorFlow 2 solution is simply replacing iterator = dataset.make_one_shot_iterator() with iterator = iter(dataset)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.