0%

添加任意数据至TensorBoard

通常情况下,我们在训练网络时添加summary都是通过如下方式:

1
2
3
4
5
6
tf.scalar_summary(tags, values)
# ...
summary_op = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(logdir, graph=sess.graph)
summary_str = sess.run(summary_op)
summary_writer.add_summary(summary_str, global_step)

当我们自己想添加其他数据到TensorBoard的时候(例如验证时的loss等),这种方式显得太过繁琐,其实我们可以通过如下方式添加自定义数据到TensorBoard内显示。

1
2
3
4
5
6
7
summary_writer = tf.summary.FileWriter(logdir)
summary = tf.Summary(value=[
tf.Summary.Value(tag="summary_tag", simple_value=0),
tf.Summary.Value(tag="summary_tag2", simple_value=1),
])
# step代表横轴坐标
summary_writer.add_summary(summary, step)

或者:

1
2
3
4
5
6
summary_writer = tf.summary.FileWriter(LOGDIR)
summary = tf.Summary()
summary.value.add(tag="summary_tag", simple_value=0)
summary.value.add(tag="summary_tag2", simple_value=1)
# step代表横轴坐标
summary_writer.add_summary(summary, step)

注意,这里的step只能是整数,如果是小数的话会自动转为整数类型。

下面给出一段完整的示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tensorflow as tf
summary_writer = tf.summary.FileWriter('/tmp/test')
summary = tf.Summary(value=[
tf.Summary.Value(tag="summary_tag", simple_value=0),
tf.Summary.Value(tag="summary_tag2", simple_value=1),
])
summary_writer.add_summary(summary, 1)

summary = tf.Summary(value=[
tf.Summary.Value(tag="summary_tag", simple_value=1),
tf.Summary.Value(tag="summary_tag2", simple_value=3),
])
summary_writer.add_summary(summary, 2)

summary_writer.close()

显示效果如下所示:sample

参考资料:

How to manually create a tf.Summary()

更新记录

2017/3/15 更新标题,修改代码兼容TensorFlow1.0版本…