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的双层通道 ...
随机推荐
- html 适配iphone X 底部导航
html 适配iphone X 底部导航 适配手机底部有横线的手机,以免被横线遮挡 padding-bottom: constant(safe-area-inset-bottom); /* 兼容 iO ...
- discuz论坛个人空间自定义css样式
Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` discuz论坛个人空间自定义css样式 日期:2020- ...
- 超越datetime:Arrow,Python中的日期时间管理大师
介绍 Arrow是一个Python库,它提供了一种合理且对人类友好的方法来创建.操作.格式化和转换日期.时间和时间戳.它实现了对datetime类型的更新,填补了功能上的空白,提供了一个智能的模块AP ...
- .NET 个人博客-发送邮件优化🧐
个人博客-发送邮件优化 前言 之前的发送邮件就弄了个方法,比如回复评论会给评论的人发送邮件,留言回复也是,而且2者的代码有很多一样的地方,比较冗余.然后也是抽空优化一下,思路也是比较常用的工厂+策略模 ...
- NXP i.MX 8M Mini工业级核心板规格书(四核ARM Cortex-A53 + 单核ARM Cortex-M4,主频1.6GHz)
1 核心板简介 创龙科技SOM-TLIMX8是一款基于NXP i.MX 8M Mini的四核ARM Cortex-A53 + 单核ARM Cortex-M4异构多核处理器设计的高端工业级核心板,AR ...
- [UG 二次开发 python] 导出BOM表(包含图片)
只导出最底层的零件,零件的属性已经设置好,零件的截图生成后,放在零件的同一个文件夹下 用到了 xlsxwriter # nx: threaded # 导出BOM表 __version__ = &quo ...
- 记一次debian无法启动的解决经历
前言 有几台debian物理机突然无法开机了,断电重启后,一直卡在下面这个界面 参考了博客[linux]解决系统卡在ubuntu loading initial ramdisk 发现无法修复 在rec ...
- Nuxt框架中内置组件详解及使用指南(一)
title: Nuxt框架中内置组件详解及使用指南(一) date: 2024/7/6 updated: 2024/7/6 author: cmdragon excerpt: 本文详细介绍了Nuxt框 ...
- CentOS7离线安装devtoolset-9并编译redis6.0.5
首先参照https://www.cnblogs.com/wdw984/p/13330074.html,来进行如何安装Centos和离线下载rpm包. 离线下载jemalloc,上传到CentOS的/d ...
- C# NPOI 读取Excel数据,附案例源码
项目结构 注意:需要引入NPOI类库 C#代码 Form1.cs using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; u ...