python - 为 tf.contrib.learn.Estimator 使用 input_fn 时设置 batch_size

标签 python tensorflow

我在 TF 上使用高级 Estimator:

estim = tf.contrib.learn.Estimator(...)
estim.fit ( some_input )

如果 some_inputxybatch_size,代码运行但有警告;所以我尝试使用input_fn,并设法通过这个input_fn发送xy,但没有发送batch_size。没有找到任何例子。

谁能分享一个使用 input_fn 作为 estim.fit/estim.evaluate 的输入并使用 的简单示例batch_size 还有吗?

我必须使用 tf.train.batch 吗?如果是这样,它如何合并到更高级别的实现 (tf.layers) - 我不知道图形的 tf.Graph() 或 session ?

下面是我收到的警告:

WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/monitors.py:657: calling evaluate

(from tensorflow.contrib.learn.python.learn.estimators.estimator) with y is deprecated and will be removed after 2016-12-01.

Instructions for updating: Estimator is decoupled from Scikit Learn interface by moving into separate class SKCompat. Arguments x, y and batch_size are only available in the SKCompat class, Estimator will only accept input_fn.

Example conversion:

est = Estimator(...) -> est = SKCompat(Estimator(...))

最佳答案

link provided in Roi's own comment确实很有帮助。由于我也为同样的问题苦苦挣扎了一段时间,所以我想总结一下上面链接提供的答案作为引用:

def batched_input_fn(dataset_x, dataset_y, batch_size):
    def _input_fn():
        all_x = tf.constant(dataset_x, shape=dataset_x.shape, dtype=tf.float32)
        all_y = tf.constant(dataset_y, shape=dataset_y.shape, dtype=tf.float32)
        sliced_input = tf.train.slice_input_producer([all_x, all_y])
        return tf.train.batch(sliced_input, batch_size=batch_size)
    return _input_fn

然后可以像这个例子一样使用它(使用 TensorFlow v1.1):

model = CustomModel(FLAGS.learning_rate)
estimator= tf.estimator.Estimator(model_fn=model.build(), params=model.params())

estimator.train(input_fn=batched_input_fn(
       train.features, 
       train.labels,
       FLAGS.batch_size),
    steps=FLAGS.train_steps)

不幸的是,与手动输入(使用 TensorFlows 低级 API)或使用整个数据集 train.shape[0] == batch_size 相比,这种方法大约慢 10 倍 并且根本不使用 train.sliced_input_producer()train.batch()。至少在我的机器上(仅 CPU)。我真的很想知道为什么这种方法这么慢。有什么想法吗?

已编辑:

我可以通过使用 num_threads > 1 作为 train.batch() 的参数来加快速度。在具有 2 个 CPU 的 VM 上,与默认的 num_threads=1 相比,我能够使用此批处理机制将性能提高一倍。但是,它仍然比手动喂食慢 5 倍。 但是在 native 系统或将所有 CPU 内核用于输入管道和 GPU 用于模型计算的系统上,结果可能会有所不同。如果有人可以在评论中发布他的结果,那就太好了。

关于python - 为 tf.contrib.learn.Estimator 使用 input_fn 时设置 batch_size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42792518/

相关文章:

Python:处理图像并保存到文件流

python - 无法导入名称包括

android - 测量 tensorflow-lite android 版本的预测精度

python - 如何配置 hive.Connection() 以将我想要的设置传递给 Hive?

python - 使用 pandas read_csv 和 nrows 读取 ~13000 行 CSV 文件的部分内容

python - 我可以在构造函数方法之外声明 Python 类字段吗?

python - Tensorflow 如何处理一列中具有多个输入的分类特征?

python - LSTM 奇偶校验生成器

tensorflow - 如何使用 tensorflow 2.0 将图形写入 tensorboard?

tensorflow - TensorFlow AttributeError : Tensor.op is meaningless when eager execution is enabled