一. 简介
tensorflow 配套的可视化工具, 能够可视化
- 静态的: 计算图的拓扑结构.
- 动态的标量: 训练过程中关心的 learning rate, loss, eval_metric 等的变化趋势.
- 动态的 tensor: 值的分布, text, image 等多媒体数据.
原理:
使用相关 api 在 tf 运行时记录下 events file, tf-board 负责对其解析和展现.
它是 protobuffer 格式, 并非文本文件.
二. 与 pytorch 搭配
2023.01 新增, 插在前面.
因为 torch 的 Tensor 与 tf 的Tensor 有差异, 所以用到了 三方库 tensorboardX 作中转. 需要 pip install tensorboardX
.
因为三方包相当于 wrapper, 与原生的 api 近乎一致, 不再赘述.
代码例子
import torch
from tensorboardX import SummaryWriter
sw = SummaryWriter()
for step in range(100):
sw.add_scalar('y', torch.rand(1)[0], global_step=step)
sw.close()
可视化效果
与上文代码对应的.
计算图的可视化
这里需要额外的编码. 用到了
SummaryWriter.add_graph(self, model, input_to_model)
内部用到了 torch 自己的 api,torch.utils.tensorboard._pytorch_graph.graph()
.
三. api
- tensorflow.python.summary.writer.writer.
FileWriter
(SummaryToEventTransformer)
类.__init__(self, logdir, graph=None,...)
构造函数, Creates aFileWriter
and an event file.
tensorflow.python.summary.summary
模块.scalar(name, tensor, ..)
Outputs aSummary
protocol buffer containing a single scalar value.histogram(name, values, collections=None, family=None)
Adding a histogram summary makes it possible to visualize your data’s distribution in TensorBoard.
Q: FileWriter 与 summary 是怎么关联起来的呢?
A: 通过 filewriter.add_summary(summary) api, 例子见下:
import tensorflow as tf
# 定义一个计算图
a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)
# 创建一个 summary 节点,用于记录 c 的值
c_summary = tf.summary.scalar("c", c)
# 创建一个 filewriter 对象,指定保存路径
filewriter = tf.summary.FileWriter("./logs")
with tf.Session() as sess:
# 初始化所有变量
sess.run(tf.global_variables_initializer())
# 将摘要数据写入文件
summary = sess.run(c_summary)
filewriter.add_summary(summary)
3.1 image
作图, 对于 grap-scale 图来讲, 0表示全黑, 255表示全白.
- api,
image(name, tensor, max_outputs=3, collections=None, family=None)
Outputs aSummary
protocol buffer with images.
images are built fromtensor
which must be 4-D with shape[batch_size, height, width, channels]
and wherechannels
can be:
- 1-
tensor
is interpreted as Grayscale. - 3-
tensor
is interpreted as RGB. - 4-
tensor
is interpreted as RGBA.
- tensor为
float
: 此时, tf会内部作正规化处理, 转换到[0,255](解析 tf_events 即可验证), float通常对应于 softm 之后的概率, 值域为[0,1]. - tensor为
uint8
, 保持不变, tf 不作任何内部转换.
3.2 attention 可视化
attention 的权重会作 soft-max 处理, 通常img显示的效果是, 一行看下来有深有浅, 颜色越白weight越大. 但有时后tf内部正规化不符合预期, 出现一行全白的情况, 稳妥起见自己转unit
类型.
四. tf-board 启动
这是一个 web 服务, 在命令行中 敲tensorboard --logdir=D:\tf_models\iris
, 根据提示打开URL即可.
比如我的为http://yichu-amd:6006/
.
效果截图
图3-1 logdir中的文件
图3-2 炫酷的可视化效果
figure 3-3 计算图的可视化
注意: 只用 saver.save() 方法, 虽然 xx.meta 文件内有计算图的拓扑, 但 tf-board 并不会解析它(虽然 netron 等可以).
小贴士
- 网络也是分模块,有结构的, 合理使用
scope
可以让计算图清晰优雅. - 有些tensor来自dataset, 有些来自api中op操作的输出, 本身没有明确的名字, 此时用
x=tf.identity(x,'name')
给tensor起名字, 便于计算图中定位. 图3-3 中的memory
就是 encoder 的输出的tensor.