[pytorch入门] 2. tensorboard

tensorboard简介

TensorBoard 是一组用于数据可视化的工具。它包含在流行的开源机器学习库 Tensorflow 中.但是也可以独立安装,服务Pytorch等其他的框架

可以常常用来观察训练过程中每一阶段如何输出的

  • 安装

    pip install tensorboard
    
  • 启动

    python 复制代码
    tensorboard --logdir=<directory_name>

    会默认在6006端口打开,也可以自行制定窗口,如:

    python 复制代码
    tensorboard --logdir=logs --port=6007

用法

  1. 所在类:

    python 复制代码
    from torch.utils.tensorboard import SummaryWriter

    介绍:

    python 复制代码
    class SummaryWriter:
        """Writes entries directly to event files in the log_dir to be
        consumed by TensorBoard.
    
        The `SummaryWriter` class provides a high-level API to create an event file
        in a given directory and add summaries and events to it. The class updates the
        file contents asynchronously. This allows a training program to call methods
        to add data to the file directly from the training loop, without slowing down
        training.
        """
  2. 创建对象

    python 复制代码
    writer = SummaryWriter('logs') # 说明写入哪个文件夹
  3. 常用方法

    python 复制代码
    writer.add_image()   # 图像方式
    writer.add_scalar()  # 坐标方式
    
    writer.close()  # 使用完之后需要close

add_scalar()

python 复制代码
    def add_scalar(self,tag,scalar_value,global_step=None,walltime=None,new_style=False,double_precision=False,):
    """Add scalar data to summary.
        添加标量数据到summary中

        Args:
            tag (str): Data identifier 图表标题
            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
            new_style (boolean): Whether to use new style (tensor field) or old
              style (simple_value field). New style could lead to faster data loading.
        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 %

        """

注意:向writer中写入新事件的同时她也会保留上一个事件,这就会导致一些拟合出现问题

解决:删除之前的log文件,重新生成

add_image()

python 复制代码
    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 (str): Data identifier
            img_tensor (torch.Tensor, numpy.ndarray, 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 event
            dataformats (str): Image data format specification of the form
              CHW, HWC, HW, WH, etc.
        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``.
            """

实践

如在tensorboard中展示图片:

python 复制代码
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image

writer = SummaryWriter('logs')
image_path = './dataset2/train/ants_image/0013035.jpg'
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)

writer.add_image("test",img_array,1,dataformats='HWC') # 展示读取的图片


for i in range(100):
    writer.add_scalar('y=2x', 3*i, i)     # 绘图

writer.close()
  • writer.add_image中的参数

    python 复制代码
    def add_image(
            self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW"
        ):

    名称、图形向量(ndarray类型),第几步(是滑动翻页那种的,这里相当于设定是第几页,每次向后设定时不会清除原来的数据)

当前代码效果如图:

修改图片后:

python 复制代码
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image

writer = SummaryWriter('logs')
image_path = './dataset2/train/ants_image/5650366_e22b7e1065.jpg'
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
print(type(img_array))
print(img_array.shape)

# 这里更新,说明为第二步
writer.add_image("test",img_array,2,dataformats='HWC')


for i in range(100):
    writer.add_scalar('y=2x', 3*i, i)

writer.close()

拖拉就会发现有两张图

相关推荐
池央15 分钟前
AI性能极致体验:通过阿里云平台高效调用满血版DeepSeek-R1模型
人工智能·阿里云·云计算
我们的五年16 分钟前
DeepSeek 和 ChatGPT 在特定任务中的表现:逻辑推理与创意生成
人工智能·chatgpt·ai作画·deepseek
Yan-英杰17 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
Fuweizn19 分钟前
富唯智能可重构柔性装配产线:以智能协同赋能制造业升级
人工智能·智能机器人·复合机器人
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
taoqick2 小时前
对PosWiseFFN的改进: MoE、PKM、UltraMem
人工智能·pytorch·深度学习
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
预测模型的开发与应用研究3 小时前
数据分析的AI+流程(个人经验)
人工智能·数据挖掘·数据分析
源大模型3 小时前
OS-Genesis:基于逆向任务合成的 GUI 代理轨迹自动化生成
人工智能·gpt·智能体