【问题标题】:How to visualize TensorFlow graph without running train/evaluate with estimator API?如何在不使用估算器 API 运行训练/评估的情况下可视化 TensorFlow 图?
【发布时间】:2019-02-20 18:09:34
【问题描述】:

如何在不运行训练或评估的情况下使用 TensorFlow 的 Estimator API 在 TensorBoard 上可视化图表?

当您可以访问 Graph 对象时,我知道它是如何使用会话 API 实现的,但找不到 Estimator API 的任何内容。

【问题讨论】:

    标签: tensorflow tensorboard


    【解决方案1】:

    估算器为您创建和管理 tf.Graphtf.Session 对象。因此,这些对象不容易访问。请注意,默认情况下,当您调用estimator.train 时,图表会导出到事件文件中。

    但是,您可以在 tf.estimator 之外调用您的 model_function,然后使用经典的 tf.summary.FileWriter() 导出图表。

    这是一个带有非常简单的估计器的代码 sn-p,它只是将密集层应用于输入:

    import tensorflow as tf
    import numpy as np
    
    # Basic input_fn
    def input_fn(x, y, batch_size=4):
        dataset = tf.data.Dataset.from_tensor_slices((x, y))
        dataset = dataset.batch(batch_size).repeat(1)
        return dataset
    
    # Basic model_fn that just apply a dense layer to an input
    def model_fn(features, labels, mode):
        global_step = tf.train.get_or_create_global_step()
    
        y = tf.layers.dense(features, 1)
    
        increment_global_step = tf.assign_add(global_step, 1)
    
        return tf.estimator.EstimatorSpec(
                mode=mode,
                predictions={'preds':y},
                loss=tf.constant(0.0, tf.float32),
                train_op=increment_global_step)
    
    # Fake data
    x = np.random.normal(size=[10, 100])
    y = np.random.normal(size=[10])
    
    # Just to show that the estimator works
    estimator = tf.estimator.Estimator(model_fn=model_fn)
    estimator.train(input_fn=lambda: input_fn(x, y), steps=1)
    
    
    # Classic way of exporting the graph using placeholders and an outside call to the model_fn
    with tf.Graph().as_default() as g:
        # Placeholders
        features = tf.placeholder(tf.float32, x.shape)
        labels = tf.placeholder(tf.float32, y.shape)
    
        # Creates the graph
        _ = model_fn(features, labels, None)
    
        # Export the graph to ./graph
        with tf.Session() as sess:
            train_writer = tf.summary.FileWriter('./graph', sess.graph)
    

    【讨论】:

    • 我问这个问题的主要原因是想看看分布策略在 tensorflow 中是如何工作的。我浏览了分发策略代码(镜像策略),但无法理解 tensorflow 如何进行 all reduce 操作。我想知道他们是否在图表中添加操作来做所有减少。我没有 GPU 设备,因此无法使用分布式策略运行实际的 MNIST 模型。但我有我的答案,我确实需要图形和会话对象才能在 tensorboard 上显示图形。
    【解决方案2】:

    为了能够使用 TensorBoard 可视化图表,您必须将它放在事件文件中。如果在培训期间您使用会话图实例化编写器:

    train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', sess.graph)
    

    你应该拥有它。

    鉴于此,只需调用 tensorboard 并为其提供存储事件文件的路径:

    tensorboard --logdir=path/to/log-directory
    

    并打开图表选项卡。

    【讨论】:

    • 在使用 Tf.Estimator API 时,您很难同时访问 Session 和 Graph。
    猜你喜欢
    • 2018-08-21
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2021-01-02
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多