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的双层通道 ...
随机推荐
- 时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响
时间格式化转换及时间比较compareTo,Controller层接收参数格式化,从数据源头解决时间格式错误数据对接口的影响 /** * 时间格式的转换:在具体报错的地方做转换,可能不能从根本上面解决 ...
- boltdb 原理
简介 介绍及简单使用:https://www.cnblogs.com/daemon365/p/17690167.html 源码地址:https://github.com/etcd-io/bbolt p ...
- 【Playwright+Python】系列教程(一)环境搭建及脚本录制
前言 看到这个文章,有的同学会说: 六哥,你为啥不早早就写完python系列的文章. 因为有徒弟需要吧,如果你也想学自学,那这篇文章,可以说是我们结缘一起学习的开始吧! 如果对你有用,建议收藏和转发! ...
- Python优雅遍历字典删除元素的方法
在Python中,直接遍历字典并在遍历过程中删除元素可能会导致运行时错误,因为字典在迭代时并不支持修改其大小.但是,我们可以通过一些方法间接地达到这个目的. 1.方法一:字典推导式创建新字典(推荐) ...
- 【iOS】push控制器时隐藏tabbar,dismiss控制器时显示tabbar
在push之前将控制器的属性hidesBottomBarWhenPushed设置为yes就好. //准备要把控制器vc给push出去了 UIViewController *vc = [[UIViewC ...
- 呼吁 《上海市卫生健康“信息技术应用创新白皮书》改正 C# 被认定为A 组件是错误认知
近日,<上海市卫生健康"信息技术应用创新"白皮书>(以下简称<白皮书>)正式发布,介绍了"医疗信创核心应用适配方法.公立医院信息系统及全民健康信息 ...
- 实训day2
HTML基本介绍 编辑网页的语言,超文本标记语言,是迄今为止网络上应用最为广泛的语言,也是抱成网页文档的主要语言.HTML文本是由HTML命令组成的描述性文本,HTML命令可以说明文字.图形.动画.声 ...
- 14-vertical-aligin
01 行盒的理解 作用: 将当前行里的所有内容包裹起来 <!DOCTYPE html> <html lang="en"> <head> < ...
- .Net Framework使用Autofac实现依赖注入
.Net Framework使用Autofac实现依赖注入 前言 最近也是找了快2周的工作了,收到的面试邀请也就几个,然后有个面试题目是用asp.net mvc + Entityframework 做 ...
- 详解Web应用安全系列(4)失效的访问控制
在Web安全中,失效的访问控制(也称为权限控制失效或越权访问)是指用户在不具备相应权限的情况下访问了受限制的资源或执行了不允许的操作.这通常是由于Web应用系统未能建立合理的权限控制机制,或者权限控制 ...