原文: https://www.emperinter.info/2020/07/30/tensorboard-in-pytorch/

缘由

自己上次安装好PyTorch以及训练了一下官方的数据,今天看到了这个TensorBoard来可视化的用法,感觉不错就尝试玩了一下!自己只是尝试了一下追踪模型训练的过程,其他自己去看官网教程吧!

用法

具体详细说明请参考https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html

简单说就是:

例子

我把训练的图片分类的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

完整版代码参考

如需了解完整代码请访问: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的TensorBoard用法示例的更多相关文章

  1. Linux find 用法示例

    Linux中find常见用法示例 ·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \; find命令的参数 ...

  2. jQuery中$.fn的用法示例介绍

    $.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效,下面有个不错的示例,喜欢的朋友可以参考下 如扩展$.fn.abc(),即$.fn.abc()是对jquery ...

  3. [转]Linux中find常见用法示例

    Linux中find常见用法示例[转]·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \;find命令的参 ...

  4. oracle中to_date详细用法示例(oracle日期格式转换)

    这篇文章主要介绍了oracle中to_date详细用法示例,包括期和字符转换函数用法.字符串和时间互转.求某天是星期几.两个日期间的天数.月份差等用法 TO_DATE格式(以时间:2007-11-02 ...

  5. 腾讯云上PhantomJS用法示例

    崔庆才 前言 大家有没有发现之前我们写的爬虫都有一个共性,就是只能爬取单纯的html代码,如果页面是JS渲染的该怎么办呢?如果我们单纯去分析一个个后台的请求,手动去摸索JS渲染的到的一些结果,那简直没 ...

  6. 腾讯云上Selenium用法示例

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者:崔庆才 前言 在上一节我们学习了PhantomJS 的基本用法,归根结底它是一个没有界面的浏览器,而且运 ...

  7. BinaryOperator<T>接口的用法示例+BiFunction

    转自http://www.tpyyes.com/a/java/2017/1015/285.html 转自https://blog.csdn.net/u014331288/article/details ...

  8. Linux find常用用法示例

    在此处只给出find的基本用法示例,都是平时我个人非常常用的搜索功能.如果有不理解的部分,则看后面的find运行机制详解对于理论的说明,也建议在看完这些基本示例后阅读一遍理论说明,它是本人翻译自fin ...

  9. Go基础系列:nil channel用法示例

    Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 当未为channel分配内存时 ...

  10. Go基础系列:双层channel用法示例

    Go channel系列: channel入门 为select设置超时时间 nil channel用法示例 双层channel用法示例 指定goroutine的执行顺序 双层通道的解释见Go的双层通道 ...

随机推荐

  1. 博客更换新域名为52ecy.cn

    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` 博客更换新域名为52ecy.cn 日期:2017-10-2 ...

  2. .Net8 AddKeyedScoped键值key注册服务异常

    异常描述:This service descriptor is keyed. Your service provider may not support keyed services. 场景:.Net ...

  3. java的ConCurrentHashMap

    一般的应用的编程,用到ConCurrentHashMap的机会很少,就象大家调侃的一样:只有面试的时候才用得着. 但还是有. 网上关于这个的资料,多如牛毛,大部分是原理分析和简单例子. 原理的核心就一 ...

  4. java+SpringCloud开发的性能和环保问题

    对于大部分商业应用开发程序员而言,使用java+spring是一件幸福的事情. 一般情况下,我们使用cloud开发不是那么重要.精密的应用,这些应用包括例如大型的商业交易,社区等等. 因为这些应用天然 ...

  5. 03-vi和vim编辑器的使用

    背景 vim是一个类似于vi的著名的功能强大.高度可定制的文本编辑器. vim在vi的基础上改进和增加了很多特性. 如今vi已经是最受IT届欢迎的编辑器之一. 不止在Linux中,主流IDE都支持vi ...

  6. Android Framework:如何让 App 拿到Power key 值

    Android app:如何让 App 拿到Power key 值 原文(有删改):https://blog.csdn.net/qq_37858386/article/details/10383566 ...

  7. HDFS的特点和目标,不适合场景

     HDFS的特点和目标: HDFS设计优点: (一)高可靠性:Hadoop按位存储和处理数据的能力值得人们信赖; (二)高扩展性:Hadoop是在可用的计算机集簇间分配数据并完成计算任务的,这些集簇可 ...

  8. 透视开源生态,OSGraph——GitHub全域数据图谱的智能洞察工具

    "透视开源生态,OSGraph--GitHub全域数据图谱的智能洞察工具 OSGraph (Open Source Graph) 是一个开源图谱关系洞察工具,基于GitHub开源数据全域图谱 ...

  9. Acwing周赛分享

    Acwing 周赛28 题面1 给定一个由大写字母构成的字符串 s,请计算其中有多少个子序列 QAQ. 注意,子序列不需要连续. 提示:本题数据范围较小,可以直接三重循环枚举三个字母的位置. 输入格式 ...

  10. 全网最适合入门的面向对象编程教程:04 类和对象的 Python 实现-为自定义类添加方法(PySerial 库接收串口数据)

    全网最适合入门的面向对象编程教程:04 类和对象的 Python 实现-为自定义类添加方法(PySerial 库接收串口数据) 摘要: 本文我们主要讲解了如何为自定义类添加方法,pyseria 库的基 ...