首页 > 解决方案 > Tensorboard Graph:Profiler 会话已启动

问题描述

我想使用 tensorflow 2 在 tensorboard 上显示我的网络图。我按照教程进行操作,并编写了如下代码:

for epoch in range(epochs):
    # Bracket the function call with
    # tf.summary.trace_on() and tf.summary.trace_export().
    tf.summary.trace_on(graph=True, profiler=True)
    # Call only one tf.function when tracing.
    z = train_step(x, y)
    with writer.as_default():
        tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)

这样做时,我收到了Profiler session started.几次消息。当然,当我打开 tensorboard 时,Graph 说发生了错误并且无法显示任何内容。

标签: tensorboardtensorflow2.0

解决方案


我在这里找到了回复。

实际上,您可以在 v2 中启用图形导出。您需要 tf.summary.trace_on()在要跟踪图形的代码之前调用(例如,如果您只想要训练步骤,则为 L224),然后 tf.summary.trace_off()在代码完成后调用。由于您只需要图形的一个跟踪,因此我建议您将这些调用包装起来,if global_step_val == 0:这样您就不会在每一步都产生跟踪。

实际上,要创建图形,只需要进行一次跟踪,并且在每个时期都进行跟踪是没有意义的。解决方案只是在调用跟踪之前检查一次,如下所示:

for epoch in range(epochs):
    if epoch == 0:
        tf.summary.trace_on(graph=True, profiler=True)
    z = train_step(x, y)
    if epoch == 0:
        with writer.as_default():
            tf.summary.trace_export(name="train_graph", step=0, profiler_outdir=logdir)

我个人更喜欢这个装饰器的想法:

def run_once(f):
    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper

@run_once
def _start_graph_tensorflow(self):
    tf.summary.trace_on(graph=True, profiler=True)  # https://www.tensorflow.org/tensorboard/graphs

@run_once
def _end_graph_tensorflow(self):
    with self.graph_writer.as_default():
        tf.summary.trace_export(name="graph", step=0, profiler_outdir=self.graph_writer_logdir)

for epoch in range(epochs):
    _start_graph_tensorflow()
    z = train_step(x, y)
    _end_graph_tensorflow()

推荐阅读