如何在tf.estimator.Estimator中使用tensorboard

Man*_*idt 11 python-3.x tensorflow tensorboard

我正在考虑将我的代码库移动到tf.estimator.Estimator,但我找不到如何将它与tensorboard摘要结合使用的示例.

MWE:

import numpy as np
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

# Declare list of features, we only have one real-valued feature
def model(features, labels, mode):
    # Build a linear model and predict values
    W = tf.get_variable("W", [1], dtype=tf.float64)
    b = tf.get_variable("b", [1], dtype=tf.float64)
    y = W*features['x'] + b
    loss = tf.reduce_sum(tf.square(y - labels))

    # Summaries to display for TRAINING and TESTING
    tf.summary.scalar("loss", loss)    
    tf.summary.image("X", tf.reshape(tf.random_normal([10, 10]), [-1, 10, 10, 1])) # dummy, my inputs are images

    # Training sub-graph
    global_step = tf.train.get_global_step()
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = tf.group(optimizer.minimize(loss), tf.assign_add(global_step, 1))

    return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss= loss,train_op=train)

estimator = tf.estimator.Estimator(model_fn=model, model_dir='/tmp/tf')
# define our data set
x=np.array([1., 2., 3., 4.])
y=np.array([0., -1., -2., -3.])
input_fn = tf.contrib.learn.io.numpy_input_fn({"x": x}, y, 4, num_epochs=1000)

for epoch in range(10):
    # train
    estimator.train(input_fn=input_fn, steps=100)
    # evaluate our model
    estimator.evaluate(input_fn=input_fn, steps=10)
Run Code Online (Sandbox Code Playgroud)

如何在tensorboard中显示我的两个摘要?我是否必须注册我使用tf.summary.FileWriter或其他东西的钩子?

jag*_*tle 14

编辑:经过测试(在v1.1.0中,也可能在更高版本中),显然tf.estimator.Estimator会自动为你编写摘要.我使用OP的代码和张量板证实了这一点.

(有些人围着r1.4引导我得出结论,这种自动摘要写作是由于tf.train.MonitoredTrainingSession.)

最终,自动摘要是通过使用钩子完成的,因此如果您想自定义Estimator的默认摘要,您可以使用钩子来完成.以下是原始答案中的(编辑过的)详细信息.


你会想要使用钩子,以前称为监视器.(链接是一个概念/快速入门指南;缺点是挂钩/监控培训的概念内置于Estimator API中.虽然有点令人困惑,但似乎并不是对挂钩的监视器的弃用是真的记录在实际源代码中的弃用注释除外...)

根据您的使用情况,看起来r1.2 SummarySaverHook适合您的账单.

summary_hook = tf.train.SummarySaverHook(
    SAVE_EVERY_N_STEPS,
    output_dir='/tmp/tf',
    summary_op=tf.summary.merge_all())
Run Code Online (Sandbox Code Playgroud)

您可能希望自定义钩子的初始化参数,例如通过提供明确的SummaryWriter或每N秒写入而不是N步骤.

如果您将其传递给EstimatorSpec,您将获得自定义的摘要行为:

return tf.estimator.EstimatorSpec(mode=mode, predictions=y,loss=loss,
                                  train_op=train,
                                  training_hooks=[summary_hook])
Run Code Online (Sandbox Code Playgroud)

编辑注:这个答案的先前版本建议传递summary_hookestimator.train(input_fn=input_fn, steps=5, hooks=[summary_hook]).这不起作用,因为tf.summary.merge_all()必须在与模型图相同的上下文中调用它.


sim*_*lmx 8

对我来说这没有添加任何钩子或merge_all调用.我刚刚添加了一些tf.summary.image(...),model_fn当我训练模型时,它们神奇地出现在张量板中.但是,不确定具体机制是什么.我正在使用TensorFlow 1.4.