PyTorch的TensorBoard用法示例

原文: https://www.emperinter.info/2020/07/30/tensorboard-in-pytorch/
缘由
自己上次安装好PyTorch以及训练了一下官方的数据,今天看到了这个TensorBoard来可视化的用法,感觉不错就尝试玩了一下!自己只是尝试了一下追踪模型训练的过程,其他自己去看官网教程吧!
用法
具体详细说明请参考https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html
简单说就是:
设置TensorBoard。
写入TensorBoard。
运行
例子
我把训练的图片分类的loss用tensorboard给可视化出来了:
步骤
- 设置TensorBoard。
简单说是设置基本tensorboard运行需要的东西,我这代码中的imshow(img)和matplotlib_imshow(img, one_channel=False)都是显示图片的函数,可以统一替换,我自己测试就没改了!
# helper function to show an image
# (used in the `plot_classes_preds` function below)
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = img / 2 + 0.5 # unnormalize
npimg = img.cpu().numpy()
if one_channel:
plt.imshow(npimg, cmap="Greys")
else:
plt.imshow(np.transpose(npimg, (1, 2, 0)))
# 设置tensorBoard
# default `log_dir` is "runs" - we'll be more specific here
writer = SummaryWriter('runs/image_classify_tensorboard')
# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
# create grid of images
img_grid = torchvision.utils.make_grid(images)
# show images
# matplotlib_imshow(img_grid, one_channel=True)
imshow(img_grid)
# write to tensorboard
writer.add_image('imag_classify', img_grid)
# Tracking model training with TensorBoard
# helper functions
def images_to_probs(net, images):
'''
Generates predictions and corresponding probabilities from a trained
network and a list of images
'''
output = net(images)
# convert output probabilities to predicted class
_, preds_tensor = torch.max(output, 1)
# preds = np.squeeze(preds_tensor.numpy())
preds = np.squeeze(preds_tensor.cpu().numpy())
return preds, [F.softmax(el, dim=0)[i].item() for i, el in zip(preds, output)]
def plot_classes_preds(net, images, labels):
'''
Generates matplotlib Figure using a trained network, along with images
and labels from a batch, that shows the network's top prediction along
with its probability, alongside the actual label, coloring this
information based on whether the prediction was correct or not.
Uses the "images_to_probs" function.
'''
preds, probs = images_to_probs(net, images)
# plot the images in the batch, along with predicted and true labels
fig = plt.figure(figsize=(12, 48))
for idx in np.arange(4):
ax = fig.add_subplot(1, 4, idx+1, xticks=[], yticks=[])
matplotlib_imshow(images[idx], one_channel=True)
ax.set_title("{0}, {1:.1f}%\n(label: {2})".format(
classes[preds[idx]],
probs[idx] * 100.0,
classes[labels[idx]]),
color=("green" if preds[idx]==labels[idx].item() else "red"))
return fig
- 写入TensorBoard。
这个在训练的每一阶段写入tensorboard
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
# 把数据写入tensorflow
# ...log the running loss
writer.add_scalar('image training loss',
running_loss / 2000,
epoch * len(trainloader) + i)
# ...log a Matplotlib Figure showing the model's predictions on a
# random mini-batch
writer.add_figure('predictions vs. actuals',
plot_classes_preds(net, inputs, labels),
global_step=epoch * len(trainloader) + i)
- 运行
tensorboard --logdir=runs

- 打开http://localhost:6006/ 即可查看

完整版代码参考
如需了解完整代码请访问:https://www.emperinter.info/2020/07/30/tensorboard-in-pytorch/
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from datetime import datetime
from torch.utils.tensorboard import SummaryWriter
..............
..............
..............
参考
- 用PyTorch训练一个图像分类
- TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
PyTorch的TensorBoard用法示例的更多相关文章
- Linux find 用法示例
Linux中find常见用法示例 ·find path -option [ -print ] [ -exec -ok command ] {} \; find命令的参数 ...
- jQuery中$.fn的用法示例介绍
$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效,下面有个不错的示例,喜欢的朋友可以参考下 如扩展$.fn.abc(),即$.fn.abc()是对jquery ...
- [转]Linux中find常见用法示例
Linux中find常见用法示例[转]·find path -option [ -print ] [ -exec -ok command ] {} \;find命令的参 ...
- oracle中to_date详细用法示例(oracle日期格式转换)
这篇文章主要介绍了oracle中to_date详细用法示例,包括期和字符转换函数用法.字符串和时间互转.求某天是星期几.两个日期间的天数.月份差等用法 TO_DATE格式(以时间:2007-11-02 ...
- 腾讯云上PhantomJS用法示例
崔庆才 前言 大家有没有发现之前我们写的爬虫都有一个共性,就是只能爬取单纯的html代码,如果页面是JS渲染的该怎么办呢?如果我们单纯去分析一个个后台的请求,手动去摸索JS渲染的到的一些结果,那简直没 ...
- 腾讯云上Selenium用法示例
欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者:崔庆才 前言 在上一节我们学习了PhantomJS 的基本用法,归根结底它是一个没有界面的浏览器,而且运 ...
- BinaryOperator<T>接口的用法示例+BiFunction
转自http://www.tpyyes.com/a/java/2017/1015/285.html 转自https://blog.csdn.net/u014331288/article/details ...
- Linux find常用用法示例
在此处只给出find的基本用法示例,都是平时我个人非常常用的搜索功能.如果有不理解的部分,则看后面的find运行机制详解对于理论的说明,也建议在看完这些基本示例后阅读一遍理论说明,它是本人翻译自fin ...
- Go基础系列:nil channel用法示例
Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 当未为channel分配内存时 ...
- Go基础系列:双层channel用法示例
Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 双层通道的解释见Go的双层通道 ...
随机推荐
- spring.jackson 相差8小时,restful接收Date参数处理
spring.jackson 相差8小时,restful接收Date参数处理 前端提交字符串到后台映射日期类型的话,加上@DateTimeFormat(pattern = "yyyy-M ...
- 从 Modbus 到 Web 数据可视化之 WebSocket 实时消息
前言 工业物联网是一个范围很大的概念,本文从数据可视化的角度介绍了一个最小化的工业物联网平台,从 Modbus 数据采集到前端数据可视化呈现的基本实现思路.这里面主要涉及基于 Modbus 通讯规约的 ...
- Blender练习——SciFi枪械.md
Blender练习--SciFi枪械 一.基本操作 常用快捷键 E 挤出 B 倒角,中途可通过滚轮或S来调整细分 Alt+点选 循环选择 Ctrl Alt+点选 并排选择 F 补面,比如一个碗口,将碗 ...
- C# 语言在AGI 赛道上能做什么
自从2022年11月OpenAI正式对外发布ChatGPT依赖,AGI 这条赛道上就挤满了重量级的选手,各大头部公司纷纷下场布局.原本就在机器学习.深度学习领域占据No.1的Python语言更是继续稳 ...
- EasyExcel 无法读取图片?用poi写了一个工具类
在平时的开发中,经常要开发 Excel 的导入导出功能.一般使用 poi 或者 EasyExcel 开发,使用 poi 做 excel 比较复杂,大部分开发都会使用 EasyExcel 因为一行代码就 ...
- Ubuntu 18.04 安装OneDrive自动同步
Ubuntu 18.04 安装OneDrive自动同步 Windows10系统已经自带了OneDrive的自动同步功能,对于多设备用户而言已经成为了一个非常方便传输保存文件的途径,在Ubuntu下也有 ...
- USB OTG有关协议
想了解USB OTG的工作原理,需要知道三个协议: ADP:Attach Detection Protocol HNP:Host Negotiation Protocol SRP:Session Re ...
- Linux系统获取开发板的文件系统并打包成img文件
应用情形: 在实际的开发中,由于原系统包含的功能有限,而根据项目的需要,安装了相应的库及运行项目程序所创建的各种文件,和所做 的各种配置,想将调试好的系统打包发布,进行批量生产,就可参考本文提供的方法 ...
- 面试官:你了解git cherry-pick吗?
事情要从一次不规范的代码开发开始说起 背景故事 时间 2024年某个风平浪静的周五晚上 地点 中国,北京,西二旗,某互联网大厂会议室 人物 小杰,小A,小B,老K 对话 老K:昨天提交的代码被测试打回 ...
- java实现微信登录
前言 上一篇做了php的微信登录,所以也总结一下Java的微信授权登录并获取用户信息这个功能的开发流程. 配置 配置什么的就不多说了,详细的配置可以直接前往我上一篇查看. https://www.cn ...