安装
虽然在pytorch下,但是其实是内核是 tensorflow里面的board,所以安装之前得先安装 tensorflow
pip install tensorflow
pip install tensorboard
add_scalar
import numpy as np
from tensorboardX import SummaryWriter
with SummaryWriter() as tb_writer:
for epoch in range(100):
tb_writer.add_scalar('scalars/test',np.random.rand(),epoch)
tb_writer.add_scalars('scalars/test2', {'xsinx': epoch*np.sin(epoch), 'xcosx':epoch*np.cos(epoch)}, epoch)
打开TensorBoard
在runs同级目录下使用命令行:
tensorboard --logdir runs
add_graph
import torch
import torchvision
from torch.autograd import Variable
from tensorboardX import SummaryWriter
# 模拟输入数据
input_data = Variable(torch.rand(16, 3, 224, 224))
# 从torchvision中导入已有模型
net = torchvision.models.resnet18()
# 声明writer对象
with SummaryWriter() as writer:
writer.add_graph(net, (input_data,))
add_image
传递给网络的图片格式往往是 [B,C,H,W] ,范围[0, 1],数据类型tensor.FloatTensor,但是add_iamge() 能够接受的格式是[C,H,W], 范围[0,1],数据类型tensor.FloatTensor。
一个是三维的,一个是四维的,这很好解决,我们把每个batch的第一张图拿出来就行了:inptu[0]的形状就是[C,H,W],符合输入要求。
with SummaryWriter() as writer:
writer.add_image('input', input_img[0].cpu(), 0)
可视化多通道feature map
用torchvision.utils.make_grid( )函数
def make_grid(tensor, nrow=8, padding=2,normalize=False, range=None, scale_each=False, pad_value=0)
把输入的特征图做一个归一化,把参数normalize设置为True即可,它能帮我们把数据的输入范围调整至[0, 1]之间,把多个feature map 拼成一张nrow列的大图,每张图的间距为padding
feature_map的shape为[B, C, H, W], 需要转为[C, 1, H, W]再传给make_grid
若某层feature map的shape为[1, 8, 128, 256],经过
feature_map.squeeze().unsqueeze(dim=1)
就变为[8, 1, 128, 256]
再保存
tb_writer.add_image('h1_conv1', make_grid(feature_map.squeeze().unsqueeze(dim=1), nrow=4, padding=20, normalize=True, scale_each=True, pad_value=1), 0)