一、tensorboard的使用

1. 导包

from torch.utils.tensorboard import SummaryWriter
如果报错:
image.png
参照博客解决:戳!


2.1 插入数据(add_scalar)

  1. # 事件文件文件夹名称
  2. writer = SummaryWriter("logs")
  3. # 插入数据
  4. for i in range(100):
  5. # 先纵坐标,后横坐标
  6. writer.add_scalar("y=2x", 2*i, i)
  7. """
  8. add_scalar参数设置
  9. Args:
  10. # 标题
  11. tag (string): Data identifier
  12. # 数据,纵坐标
  13. scalar_value (float or string/blobname): Value to save
  14. # 横坐标
  15. global_step (int): Global step value to record
  16. """
  17. writer.close()

运行会在文件夹内生成事件文件。
image.png

2.2 插入图片(add_image)

  • 安装opencv读取图片:pip install opencv-python

    1. import cv2
    2. img = cv2.imread(path)

    或者:

    1. from PIL import Image
    2. import numpy as np
    3. img = Image.open(path)
    4. img_array = np.array(img)
  • 插入图片 ```python

    设置文件夹名称

    writer = SummaryWriter(“logs”)

    图片路径

    img_path = “data/train/ants/0013035.jpg”

    读取图片为np格式

    img_PIL = Image.open(img_path) img_array = np.array(img_PIL)

默认格式为:(通道数, 高度, 宽度)

如果通道数在后面,则使用dataformats参数设置为”HWC”

writer.add_image(“test”, img_array, 1, dataformats=’HWC’) “”” Args: tag: Data identifier

图片

  1. img_tensor: An `uint8` or `float` Tensor of shape `
  2. [channel, height, width]` where `channel` is 1, 3, or 4.
  3. The elements in img_tensor can either have values
  4. in [0, 1] (float32) or [0, 255] (uint8).
  5. Users are responsible to scale the data in the correct range/type.

第几张图片(在同一个tag下面的所有图片可以滑动)

  1. global_step: Global step value to record
  2. walltime: Optional override default walltime (time.time()) of event.
  3. dataformats: This parameter specifies the meaning of each dimension of the input tensor.

默认格式为:(通道数, 高度, 宽度)

如果通道数在后面,则使用dataformats参数设置为”HWC”

  1. Shape:
  2. img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to
  3. convert a batch of tensor into 3xHxW format or use ``add_images()`` and let us do the job.
  4. Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitible as long as
  5. corresponding ``dataformats`` argument is passed. e.g. CHW, HWC, HW.

“”” writer.close() ``` image.png

3. 打开事件文件

控制台:tensorboard --logdir=[文件夹名称]
例如:tensorboard --logdir=logs
会默认在6006端口打开
重新设置端口号:tensorboard --logdir=[文件夹名称] --port=6007
image.png