三、TensorBoard

一、安装TensorBoard

管理员身份运行Anaconda Prompt,进入自己的环境环境 conda activate y_pytorchpip install tensorboard 进行下载,也可以通过conda install tensorboard进行下载。其实通俗点,pip相当于菜市场,conda相当于大型正规超市。
在这里插入图片描述

二、SummaryWriter类

所有编译均在PyChram下进行

from torch.utils.tensorboard import SummaryWriter

按着Ctrl,点击SummaryWriter,进入查看该类的使用说明文档
在这里插入图片描述

    """Writes entries directly to event files in the log_dir to beconsumed by TensorBoard.  将条目直接写入log_dir中的事件文件,供TensorBoard使用The `SummaryWriter` class provides a high-level API to create an event filein a given directory and add summaries and events to it. The class updates thefile contents asynchronously. This allows a training program to call methodsto add data to the file directly from the training loop, without slowing downtraining."""看不懂没关系,DL翻译一下就行了呗,大概就是,SummaryWriter类会生成一个文件,这个文件会被TensorBoard所解析使用,也就是说可以通过TensorBoard进行可视化展示
#这个是SummaryWriter的初始化函数def __init__(self, log_dir=None, comment='', purge_step=None, max_queue=10,flush_secs=120, filename_suffix=''):"""Creates a `SummaryWriter` that will write out events and summariesto the event file.Args:log_dir (string): Save directory location. Default isruns/**CURRENT_DATETIME_HOSTNAME**, which changes after each run.Use hierarchical folder structure to comparebetween runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.for each new experiment to compare across them.
#保存的文件为log_dir所指定的位置,默认为runs/**CURRENT_DATETIME_HOSTNAME**这个位置#同理,后面的参数可以进行翻译,然后进行学习即可comment (string): Comment log_dir suffix appended to the default``log_dir``. If ``log_dir`` is assigned, this argument has no effect.purge_step (int):When logging crashes at step :math:`T+X` and restarts at step :math:`T`,any events whose global_step larger or equal to :math:`T` will bepurged and hidden from TensorBoard.Note that crashed and resumed experiments should have the same ``log_dir``.max_queue (int): Size of the queue for pending events andsummaries before one of the 'add' calls forces a flush to disk.Default is ten items.flush_secs (int): How often, in seconds, to flush thepending events and summaries to disk. Default is every two minutes.filename_suffix (string): Suffix added to all event filenames inthe log_dir directory. More details on filename construction intensorboard.summary.writer.event_file_writer.EventFileWriter.Examples::
#如何使用,使用案例from torch.utils.tensorboard import SummaryWriter# create a summary writer with automatically generated folder name.writer = SummaryWriter()# folder location: runs/May04_22-14-54_s-MacBook-Pro.local/
#参数啥都不加,默认生成的文件会放入runs/May04_22-14-54_s-MacBook-Pro.local/位置# create a summary writer using the specified folder name.writer = SummaryWriter("my_experiment")# folder location: my_experiment
#指定位置,生成的文件会放入指定位置# create a summary writer with comment appended.writer = SummaryWriter(comment="LR_0.1_BATCH_16")# folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/"""

了解完SummaryWriter之后,开始为其创建对象

writer = SummaryWriter("y_log")#对应生成的文件会放入y_log文件夹下

三、add_scalar()方法

将标量数据添加到summary中

writer.add_scalar()#按住Ctrl,点击add_scalar方法,查看该方法的使用说明

在这里插入图片描述

        """Add scalar data to summary.
#将标量数据添加到summary中Args:#参数tag (string): Data identifier
#图标的title名称scalar_value (float or string/blobname): Value to save
#要保存的数据值,一般用作y轴global_step (int): Global step value to record
#记录全局的步长值,一般用作x轴walltime (float): Optional override default walltime (time.time())with seconds after epoch of eventnew_style (boolean): Whether to use new style (tensor field) or oldstyle (simple_value field). New style could lead to faster data loading.Examples::from torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter()x = range(100)for i in x:writer.add_scalar('y=2x', i * 2, i)writer.close()Expected result:.. image:: _static/img/tensorboard/add_scalar.png:scale: 50 %"""

绘制一个y=3*x的图,通过tensorboard进行展示

from torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter("y_log")#文件所存放的位置在y_log文件夹下for i in range(100):writer.add_scalar("y=3*x",3*i,i)#图标的title为y=3*x,y轴为3*i,x轴为i
#要注意的是title若一样,则会发生拟合现象,会出错。一般不同图像要对应不同的title,一个title会对应一张图。writer.close()

运行完之后,发现多了个文件夹,里面存放的就是tensorboard的一些事件文件
在这里插入图片描述
Terminal下运行tensorboard --logdir=y_log --port=7870,logdir为打开事件文件的路径,port为指定端口打开;
通过指定端口7870进行打开tensorboard,若不设置port参数,默认通过6006端口进行打开。
在这里插入图片描述
点击该链接或者复制链接到浏览器打开即可
在这里插入图片描述

四、add_image()方法

将图像数据添加到summary中
同样的道理,进行查看该方法的使用说明

writer.add_image()#按住Ctrl,点击aadd_image方法,查看该方法的使用说明

在这里插入图片描述

        """Add image data to summary.
#将图像数据添加到summary中Note that this requires the ``pillow`` package.Args:#参数tag (string): Data identifier
#对数据的定义,也就是在tensorboard中显示的时候title是啥            img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data
#这里对图像的要求必须是这几类,需要将图片类型进行转换global_step (int): Global step value to record
#记录的全局步长,也就是第几张图片walltime (float): Optional override default walltime (time.time())seconds after epoch of eventShape:img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` toconvert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job.Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long ascorresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``.
##图片的类型应该为(3, H, W),若不一样则可以通过dataformats参数进行设置Examples::from torch.utils.tensorboard import SummaryWriterimport numpy as npimg = np.zeros((3, 100, 100))img[0] = np.arange(0, 10000).reshape(100, 100) / 10000img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000img_HWC = np.zeros((100, 100, 3))img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000writer = SummaryWriter()writer.add_image('my_image', img, 0)# If you have non-default dimension setting, set the dataformats argument.writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC')writer.close()Expected result:.. image:: _static/img/tensorboard/add_image.png:scale: 50 %"""

添加图片到tensorboard中

from torch.utils.tensorboard import SummaryWriter
import cv2 as cv
import numpy as npwriter = SummaryWriter("y_log")img_path = "G:/PyCharm/workspace/learning_pytorch/dataset/a/1.jpg"
img = cv.imread(img_path)
img_array = np.array(img)
print(type(img_array))#<class 'numpy.ndarray'>    满足该方法img_tensor类型
print(img_array.shape)#(499, 381, 3)    这里看到是(H, W, 3),并不是人家指定的(3, H, W),需要设置dataformats来声明该数据规格为HWCwriter.add_image("beyond",img_array,0,dataformats="HWC")#将来在tensorbord显示的title为beyondwriter.close()

在这里插入图片描述
Terminal下运行tensorboard --logdir=y_log --port=7870,logdir为打开事件文件的路径,port为指定端口打开;
通过指定端口7870进行打开tensorboard,若不设置port参数,默认通过6006端口进行打开。
在这里插入图片描述
点击该链接或者复制链接到浏览器打开即可
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/377598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

IT资产管理系统SQL版

你难道还在用Excel登记IT资产信息吗&#xff1f; 那你一定要好好考虑如何面对以下问题 1&#xff1a;IT人员需要面对自身部门以下问题用户申请了资产it部未处理的单还有哪些?库存里面还有哪些资产?有多少设备在维修?有多少设备已经报废了?哪些资产低于安全库存需要采购?使…

详细讲解设计跳表的三个步骤(查找、插入、删除)

目录写在前面跳表概要查找步骤插入步骤删除步骤完整代码写在前面 关于跳表的一些知识可以参考这篇文章,最好是先看完这篇文章再看详细的思路->代码的复现步骤: Redis内部数据结构详解(6)——skiplist 关于跳表的插入、删除基本操作其实也就是链表的插入和删除&#xff0c;所…

php 类静态变量 和 常量消耗内存及时间对比

在对类执行100w次循环后&#xff0c; 常量最快&#xff0c;变量其次&#xff0c;静态变量消耗时间最高 其中&#xff1a; 常量消耗&#xff1a;101.1739毫秒 变量消耗&#xff1a;2039.7689毫秒 静态变量消耗&#xff1a;4084.8911毫秒 测试代码&#xff1a; class Timer_profi…

一个机器周期 计算机_计算机科学组织| 机器周期

一个机器周期 计算机机器周期 (Machine Cycle) The cycle during which a machine language instruction is executed by the processor of the computer system is known as the machine cycle. If a program contains 10 machine language instruction, 10 separate machine …

四、Transforms

transform是torchvision下的一个.py文件&#xff0c;这个python文件中定义了很多的类和方法&#xff0c;主要实现对图片进行一些变换操作 一、Transforms讲解 from torchvision import transforms#按着Ctrl&#xff0c;点击transforms进入到__init__.py文件中 from .transfo…

leetcode 134. 加油站 思考分析

目录题目1、暴力法&#xff0c;双层遍历2、贪心题目 在一条环路上有 N 个加油站&#xff0c;其中第 i 个加油站有汽油 gas[i] 升。 你有一辆油箱容量无限的的汽车&#xff0c;从第 i 个加油站开往第 i1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发&#xff0…

单链线性表的实现

//函数结果状态代码#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 //Status是函数的类型&#xff0c;其值是函数结果状态代码 typedef int Status; typedef int ElemType;…

时间模块,带Python示例

Python时间模块 (Python time Module) The time module is a built-in module in Python and it has various functions that require to perform more operations on time. This is one of the best modules in Python that used to solve various real-life time-related pro…

五、torchvision

一、下载CIFAR-10数据集 CIFAR-10数据集官网 通过阅读官网给的解释可以大概了解到&#xff0c;一共6w张图片&#xff0c;每张图片大小为3232&#xff0c;5w张训练图像&#xff0c;1w张测试图像&#xff0c;一共由十大类图像。 CIFAR10官网使用文档 torchvision.datasets.CIF…

leetcode 69. x 的平方根 思考分析

题目 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根&#xff0c;其中 x 是非负整数。 由于返回类型是整数&#xff0c;结果只保留整数的部分&#xff0c;小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842…, 由于返回…

背包问题 小灰_小背包问题

背包问题 小灰Prerequisites: Algorithm for fractional knapsack problem 先决条件&#xff1a; 分数背包问题算法 Here, we are discussing the practical implementation of the fractional knapsack problem. It can be solved using the greedy approach and in fraction…

360浏览器兼容问题

360浏览器兼容问题 360浏览器又是一大奇葩&#xff0c;市场份额大&#xff0c;让我们不得不也对他做些兼容性处理。 360浏览器提供了两种浏览模式&#xff0c;极速模式和兼容模式&#xff0c;极速模式下是webkit内核的处理模式&#xff0c;兼容模式下是与IE内核相同的处理模式。…

转 设计师也需要了解的一些前端知识

一、常见视觉效果是如何实现的 一些事 关于文字效果 互联网的一些事 文字自身属性相关的效果css中都是有相对应的样式的&#xff0c;如字号、行高、加粗、倾斜、下划线等&#xff0c;但是一些特殊的效果&#xff0c;主要表现为ps中图层样式中的效果&#xff0c;css是无能为力的…

六、DataLoader

一、DataLoader参数解析 DataLoader官网使用手册 参数描述dataset说明数据集所在的位置、数据总数等batch_size每次取多少张图片shuffleTrue乱序、False顺序(默认)samplerbatch_samplernum_workers多进程&#xff0c;默认为0采用主进程加载数据collate_fnpin_memorydrop_las…

单调栈 leetcode整理(一)

目录单调栈知识402. 移掉K位数字1673. 找出最具竞争力的子序列316. 去除重复字母&#xff08;1081. 不同字符的最小子序列&#xff09;321. 拼接最大数单调栈知识 单调栈就是一个内部元素有序的栈&#xff08;大->小 or 小->大&#xff09;&#xff0c;但是只用到它的一…

数字签名 那些密码技术_密码学中的数字签名

数字签名 那些密码技术A signature is usually used to bind signatory to the message. The digital signature is thus a technique that binds a person or the entity to the digital data. This binding ensures that the person sending the data is solely responsible …

七、torch.nn

一、神经网络模块 进入到PyTorch的torch.nnAPI学习页面 PyTorch提供了很多的神经网络方面的模块&#xff0c;NN就是Neural Networks的简称 二、Containers torch.nn下的Containers 一共有六个模块&#xff0c;最常用的就是Module模块&#xff0c;看解释可以知道&#xff0c…

Java多线程初学者指南(8):从线程返回数据的两种方法

本文介绍学习Java多线程中需要学习的从线程返回数据的两种方法。从线程中返回数据和向线程传递数据类似。也可以通过类成员以及回调函数来返回数据。原文链接 从线程中返回数据和向线程传递数据类似。也可以通过类成员以及回调函数来返回数据。但类成员在返回数据和传递数据时有…

【C++进阶】 遵循TDD原则,实现平面向量类(Vec2D)

目录1、明确要实现的类的方法以及成员函数2、假设已经编写Vec2D&#xff0c;根据要求&#xff0c;写出测试代码3、编写平面向量类Vec2D,并进行测试4、完整代码5、最终结果1、明确要实现的类的方法以及成员函数 考虑到效率问题&#xff0c;我们一般将函数的参数设置为引用类型。…

Keilc的中断号计算方法

中断号码 (中断向量-3)/8转载于:https://www.cnblogs.com/yuqilihualuo/p/3423634.html