如何在没有 运行 train/evaluate 和估计器 API 的情况下可视化 TensorFlow 图?

How to visualize TensorFlow graph without running train/evaluate with estimator API?

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

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

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

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

你应该有它。

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

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

并打开图表选项卡。

估算器为您创建和管理 tf.Graphtf.Session 对象。因此,这些对象不容易访问。请注意,默认情况下,当您调用 estimator.train.

时,图表会导出到事件文件中

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

这是一个代码片段,其中包含一个非常简单的估计器,它只是将密集层应用于输入:

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)