当前位置:网站首页>pytorch框架学习(7) tensorboard使用
pytorch框架学习(7) tensorboard使用
2022-08-10 05:29:00 【Time.Xu】
from torch.utils.tensorboard import SummarWriter
SummarWriter 是一个写 可以被tensorboard解析 的事件文件的 类
Writes entries directly to event files in the log_dir to be consumed by TensorBoard.
’ SummaryWriter '类提供了一个高级API,可以在给定目录中创建一个事件文件,并向其中添加摘要和事件。该类异步更新文件内容。这允许训练程序调用方法直接从训练循环向文件中添加数据,而不会减慢训练速度。
以下是class SummarWriter(object)的__init__
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 summaries to the event file. Args: log_dir (string): Save directory location. Default is runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run. Use hierarchical folder structure to compare between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc. for each new experiment to compare across them. 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 be purged 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 and summaries before one of the 'add' calls forces a flush to disk. Default is ten items. flush_secs (int): How often, in seconds, to flush the pending events and summaries to disk. Default is every two minutes. filename_suffix (string): Suffix added to all event filenames in the log_dir directory. More details on filename construction in tensorboard.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/ # 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/ """
创建一个实例
writer = SummaryWriter("")
add_scalar()的使用 【向Summary中添加标量】
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
"""Add scalar data to 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 event Examples:: from torch.utils.tensorboard import SummaryWriter writer = 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 % """
torch._C._log_api_usage_once("tensorboard.logging.add_scalar")
if self._check_caffe2_blob(scalar_value):
from caffe2.python import workspace
scalar_value = workspace.FetchBlob(scalar_value)
self._get_file_writer().add_summary(
scalar(tag, scalar_value), global_step, walltime)
add_image()的使用【】
def add_image(self, tag, img_tensor, global_step=None, walltime=None, dataformats='CHW'):
"""Add image data to summary. Note that this requires the ``pillow`` package. Args: tag (string): Data identifier # 标题 img_tensor (torch.Tensor, numpy.array, or string/blobname): Image data # 注意图像的类型应该是Tensor或者numpy.array或者string/blobname global_step (int): Global step value to record # 步骤 walltime (float): Optional override default walltime (time.time()) seconds after epoch of event Shape: img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to convert 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 as corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``. Examples:: from torch.utils.tensorboard import SummaryWriter import numpy as np img = np.zeros((3, 100, 100)) img[0] = np.arange(0, 10000).reshape(100, 100) / 10000 img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 img_HWC = np.zeros((100, 100, 3)) img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 writer = 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 % """
torch._C._log_api_usage_once("tensorboard.logging.add_image")
if self._check_caffe2_blob(img_tensor):
from caffe2.python import workspace
img_tensor = workspace.FetchBlob(img_tensor)
self._get_file_writer().add_summary(
image(tag, img_tensor, dataformats=dataformats), global_step, walltime)
- 值得注意的是:输入图像的格式必须是tensor或者np.array或者str
- 格式应该是(C, H, W)否则会报错。当然可以命令来指定格式
如何打开tensorboard文件?
我经常使用的方法:
首先Win+R 输入cmd进入 Terminal后,激活相应的环境。
其次进入到events文件的所在文件夹的父级文件夹(这里是runs)
之后指定events文件的所在文件夹,命令如:tensorboard --logdir=文件夹(这里是Aug…)
最后在浏览器中把 http://localhost:6006/打开就OK了~~(下图所对应的结果展示如下下图)
- 追加一个小点(一般用不到):端口默认是6006,如果冲突了我们可以更换端口。
tensorboard --logdir=文件夹 --port=6007 就可以把端口换为6007
边栏推荐
- 基于Qiskit——《量子计算编程实战》读书笔记(四)
- 论文精读 —— 2021 CVPR《Progressive Temporal Feature Alignment Network for Video Inpainting》
- Error when installing oracle rac 11g and executing root.sh
- aliases节点分析
- 反转链表中的第m至第n个节点---leetcode
- SQL database field to append to main table
- [Thesis Notes] Prototypical Contrast Adaptation for Domain Adaptive Semantic Segmentation
- strongest brain (1)
- MongoDB 基础了解(一)
- EasyGBS connects to mysql database and prompts "can't connect to mysql server", how to solve it?
猜你喜欢
canvas canvas drawing clock
ThreadPoolExecutor thread pool principle
Interface debugging also can play this?
基于Qiskit——《量子计算编程实战》读书笔记(六)
Qiskit 学习笔记1
OAuth2 usage scenarios, common misunderstandings, use cases
How to simulate the background API call scene, very detailed!
一篇文章掌握整个JVM,JVM超详细解析!!!
基于Qiskit——《量子计算编程实战》读书笔记(七)
Zhongang Mining: Strong downstream demand for fluorite
随机推荐
反转链表中的第m至第n个节点---leetcode
oracle rac 11g安装执行root.sh时报错
基于Qiskit——《量子计算编程实战》读书笔记(三)
Depth of carding: prevent model fitting method
剑指Offer 033.变位数组
FPGA工程师面试试题集锦21~30
每周推荐短视频:探索AI的应用边界
flinkcdc 读取pgsql 的时间被放大了 有大佬知道咋回事吗 gmt_create':1
Buu Web
Ask you guys.The FlinkCDC2.2.0 version in the CDC community has a description of the supported sqlserver version, please
Concurrency tool class - introduction and use of CountDownLatch, CyclicBarrier, Semaphore, Exchanger
SQL database field to append to main table
Kubernetes:(十六)Ingress的概念和原理
canvas canvas drawing clock
CORS跨域资源共享漏洞的原理与挖掘方法
顺序表的删除,插入和查找操作
论文精度 —— 2016 CVPR 《Context Encoders: Feature Learning by Inpainting》
summer preschool assignments
Matlab simulation of multi-factor house price prediction based on BP neural network
栈与队列 | 用栈实现队列 | 用队列实现栈 | 基础理论与代码原理