简体   繁体   English

如何将Python数据生成器转换为Tensorflow张量?

[英]How to convert a Python data generator to a Tensorflow tensor?

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. 我想通过使用这个Python数据生成器将数据提供给Tensorflow模型,但我无法弄清楚如何将生成器转换为Tensorflow张量。 I'm looking for something similar to Keras' fit_generator() function. 我正在寻找类似于Keras'fit_generator()函数的东西。

Thanks! 谢谢!

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. tf.data.Dataset.from_generator()方法提供了一种将Python生成器转换为tf.Tensor对象的方法,该对象评估生成器中的每个连续元素。

Let's say you have a simple generator that generates tuples (but could alternatively generate lists or NumPy arrays): 假设您有一个生成元组的简单生成器(但也可以生成列表或NumPy数组):

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. 您可以使用tf.data API将生成器首先转换为tf.data.Dataset ,然后转换为tf.data.Iterator ,最后转换为tf.Tensor对象的元组。

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. 然后,您可以使用int_tensorfloat_tensorstr_tensor作为TensorFlow模型的输入。 See the tf.data programmer's guide for more ideas. 有关更多想法,请参阅tf.data程序员指南

There's no need to use generator for feeding data when I using pure Tensorflow. 当我使用纯Tensorflow时,不需要使用生成器来提供数据。 And when you are using Keras, why you still need to feed data with Tensorflow style?I mean there's a function fit() for Keras. 当您使用Keras时,为什么还需要使用Tensorflow样式提供数据?我的意思是Keras的函数适合()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM