在 Tensorboard 中使用 Tensorflow v2.0 显示图形

Har*_*han 6 machine-learning python-3.x tensorflow tensorboard

以下代码使用 TensorFlow v2.0

import tensorflow as tf    
a = tf.constant(6.0, name = "constant_a")
b = tf.constant(3.0, name = "constant_b")
c = tf.constant(10.0, name = "constant_c")
d = tf.constant(5.0, name = "constant_d")    
mul = tf.multiply(a, b , name = "mul")
div = tf.divide(c,d, name ="div")
addn = tf.add_n([mul, div], name = "addn")

writer = tf.summary.create_file_writer("./tensorboard")

with writer.as_default():
     tf.summary.scalar("addn_harsha", addn, step=1)
Run Code Online (Sandbox Code Playgroud)

我是 Python 和 Tensorflow 的新手。我可以使用上面的代码在 Tensorboard 中创建标量。但我无法生成相同的图表。

在 TensorFlow v1.0 中,我们这样写: writer = tf.summary.FileWriter("./tensorboard", sess.graph)

但是在 TensorFlow v2.0 中,不再使用 Session。那么,我们可以编写什么来使用 TensorFlow v2.0 在 TensorBoard 中创建图形

jde*_*esa 6

可以通过多种方式做到这一点,但有两个问题。主要的是 TensorFlow 2.0 通常在 Eager 模式下工作,因此根本没有要记录的图表。我发现的另一个问题,至少在我的安装中,是当我尝试加载带有图形的日志目录时,2.0 Tensorboard 崩溃。我想这会得到解决,但现在我只能用 Tensorboard 1.15 检查用 2.0 编写的结果图。

据我所知,至少有两种方法可以在 TensorFlow 2.0 中编写图形。现在最直接的方法是使用 Keras 模型和TensorBoard回调函数进行write_graph=True训练。这可能如下所示:

import tensorflow as tf
import numpy as np

# Make Keras model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=(10,)))
model.compile(optimizer=tf.keras.optimizers.SGD(), loss='MSE')
# Make callback
log_dir = '...'
tb_cbk = tf.keras.callbacks.TensorBoard(log_dir, write_graph=True)
# Fit to some data using the callback
x, y = np.ones((100, 10)), np.ones((100, 1))
model.fit(x, y, batch_size=5, epochs=2, callbacks=[tb_cbk])
Run Code Online (Sandbox Code Playgroud)

如果您只想将任意一段 TensorFlow 代码转换为图形,您可以使用tf.function. 这会将常规 Python 函数转换为图形,或者更好的是,可以根据需要生成图形的可调用函数,然后您可以将其保存。但是,要做到这一点,您需要一个tf.summary.graph尚不存在的假定图函数。该函数存在,但是,它只是没有在主 API 中公开(不确定他们将来是否会合并它),但是您可以通过summary_ops_v2模块访问它。你可以这样使用它:

import tensorflow as tf
from tensorflow.python.ops import summary_ops_v2

# Some function to convert into a graph
@tf.function
def my_fun(x):
    return 2 * x

# Test
a = tf.constant(10, tf.float32)
b = my_fun(a)
tf.print(b)
# 20

# Log the function graph
log_dir = '...'
writer = tf.summary.create_file_writer(log_dir)
with writer.as_default():
    # Get concrete graph for some given inputs
    func_graph = my_fun.get_concrete_function(a).graph
    # Write the graph
    summary_ops_v2.graph(func_graph.as_graph_def(), step=0)
writer.close()
Run Code Online (Sandbox Code Playgroud)

同样,在这两种情况下,我只能在 Tensorboard 的 1.x 版本中可视化结果,但生成的日志文件是正确的。