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的双层通道 ...
随机推荐
- 3个线程分别交替输出xyz字符,输出10遍
一位群友分享的**公司面试题 3个线程分别交替输出xyz字符,输出10遍 public class XYZ implements Runnable { private static AtomicInt ...
- 抖音验证签名和接口含中文签名,需要在发送端加上utf8编码
抖音验证签名和接口含中文签名,需要在发送端加上utf8编码 抖音验签和抖音异步通知回调验签解决:是对整个接收的字符串做验签,而不是部分数据做验签解决中文参数问题,否则中文乱码报验签错误 签名算法htt ...
- Thread的join方法demo
Thread的join方法demo /** * 关于join官方的解释是 Waits for this thread to die. 也就是等待一个线程结束. */ public class Thre ...
- 通俗理解GAN -- 基础认知
Smiling & Weeping ---- 你已春风摇曳,我仍一身旧雪 1.GAN的基本思想 GAN全称对抗生成网络,顾名思义是生成模型的一种,而他的训练则是一种对抗博弈状态中的.下面我们举 ...
- TGI 基准测试
本文主要探讨 TGI 的小兄弟 - TGI 基准测试工具.它能帮助我们超越简单的吞吐量指标,对 TGI 进行更全面的性能剖析,以更好地了解如何根据实际需求对服务进行调优并按需作出最佳的权衡及决策.如果 ...
- 3568F-PCIe 5G通信测试手册
- Vue手稿4
- 基于 Impala 的高性能数仓实践之物化视图服务
本文将主要介绍 NDH Impala 的物化视图实现. 接上篇,前两篇分别讲了执行引擎和虚拟数仓,它们是让一个 SQL 又快又好地执行的关键.但如果某些 SQL 过于复杂,比如多张大表进行 Join ...
- 玄机-第一章 应急响应-Linux日志分析
目录 前言 简介 应急开始 准备工作 查看auth.log文件 grep -a 步骤 1 步骤 2 步骤 3 步骤 4 步骤 5 总结 前言 又花了一块rmb玩玄机...啥时候才能5金币拿下一个应急靶 ...
- 在ubuntu16.04下,源码编译安装特定版本的MongoDB PHP扩展
背景:我的php项目在连接其他mongo库时报:Server at xxx:27017 reports wire version 5, but this version of libmongoc re ...