介绍
因为工作需要,改用pytorch。但如何将训练过程可视化成了大问题。听说pytorch代码中可以插入tensorboard代码,第一反应是居然可以这么玩。。
网络上PyTorch中使用tensorboard的方法有很多。但毕竟tensorboard不是PyTorch框架原生自带的,因此大多方法都只能支持部分功能。经过孙大佬的推荐,觉得使用tensorboardX应该是目前已知的最好方法了。
Usage
环境要求:
- pytorch>=0.3.1
Install
代码语言:javascript复制pip install tensorboardX
调用方法
- 首先要import tensorboardX: from tensorboardX import SummaryWriter
- 直接往接口喂pytorch形式的tensor即可,so方便: writer.add_histogram('zz/x', x, epoch) writer.add_scalar('data/x', x, epoch) writer.add_scalars('data/scalar_group', {'x': x, 'y': y, 'loss': loss}, epoch) writer.add_text('zz/text', 'zz: this is epoch ' str(epoch), epoch)
- 保存记录信息到.json文件里: writer.export_scalars_to_json("./test.json")
- 及时关闭writer: writer.close()
Sample code
代码语言:javascript复制import torch
from tensorboardX import SummaryWriter
writer = SummaryWriter()
x = torch.FloatTensor([100])
y = torch.FloatTensor([500])
for epoch in range(100):
x /= 1.5
y /= 1.5
loss = y - x
print(loss)
writer.add_histogram('zz/x', x, epoch)
writer.add_histogram('zz/y', y, epoch)
writer.add_scalar('data/x', x, epoch)
writer.add_scalar('data/y', y, epoch)
writer.add_scalar('data/loss', loss, epoch)
writer.add_scalars('data/scalar_group', {'x': x,
'y': y,
'loss': loss}, epoch)
writer.add_text('zz/text', 'zz: this is epoch ' str(epoch), epoch)
# export scalar data to JSON for external processing
writer.export_scalars_to_json("./test.json")
writer.close()
Demo
[1] tensorboardX开源项目:lanpa/tensorboard-pytorch