【问题标题】:setting batch_size when using input_fn for tf.contrib.learn.Estimator为 tf.contrib.learn.Estimator 使用 input_fn 时设置 batch_size
【发布时间】:2017-08-05 04:10:50
【问题描述】:

我在 TF 上使用高级 Estimator:

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

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

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

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

以下是我收到的警告:

警告:tensorflow:来自/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/monitors.py:657:调用评估

(来自 tensorflow.contrib.learn.python.learn.estimators.estimator)带 y 已被弃用,并将在 2016-12-01 之后删除。

更新说明: 通过移动到 Estimator 与 Scikit Learn 界面分离 单独的类 SKCompat。参数 x、y 和 batch_size 仅 在 SKCompat 类中可用,Estimator 将只接受 input_fn。

转换示例:

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

【问题讨论】:

  • 对于将来可能会遇到 input_fn 问题的任何人(目前我发现文档不是很容易解释) - 找到了一个很好解释的例子,在以下link.

标签: python tensorflow


【解决方案1】:

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 而不使用 train.sliced_input_producer() 和 @987654326 的整个数据集相比,这种方法大约慢 10 倍 @ 一点也不。至少在我的机器上(仅限 CPU)。我真的很想知道为什么这种方法这么慢。有什么想法吗?

已编辑:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2020-09-19
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多