P8-P9 TensorBoard的使用

一、安装

1、conda内安装

conda install -c conda-forge tensorboard

2、Pycharm内安装

找到Terminal,记得前缀要变成putorch!(如下图)
在这里插入图片描述
然后输入:

pip install tensorboard

二、使用

有一套固定流程:

writer = SummaryWriter("自定义日志文件名")

# 写

# 关闭
writer.close()

查看:
在Terminal中输入:

tensorboard --logdir=自定义日志文件名 

打开链接 -> 左上角选择SCALARS或IMAGES

(一)writer.add_scalar():常用来画train/val loss

文档说明:

    def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
        """Add scalar data to summary.

        Args:
            tag (string): Data identifier
            scalar_value (float or string/blobname): Value to save
            global_step (int): Global step value to record 训练步骤
            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()

(二)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
            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()

1、准备数据集

from PIL import Image
image_path = "data/train/bees_image/132826773_dbbcb117b9.jpg"
img_PIL = Image.open(image_path)
print(type(img_PIL)  # 可以看到是PIL类型

2、利用Opencv读取图片,获取numpy型图片数据
安装:

pip install opencv-python==4.3.0.38

ps:P11才继续讲

3、利用numpy.array()对PIL图片进行转换(PIL->numpy)

import numpy as np
img_array = np.array(img_PIL)  # img->img_array

完整代码

from torch.utils.tensorboard import SummaryWriter
import numpy as np
from PIL import Image

writer = SummaryWriter("logs")
image_path = "data/train/bees_image/132826773_dbbcb117b9.jpg"
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
writer.add_image("test2", img_array, 1, dataformats='HWC')
# 测试
print(type(img_array))  # <class 'numpy.ndarray'>
print(img_array.shape)  # (334, 500, 3)

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

writer.close()

ps img_array.shape=(334, 500, 3),三个值分别对应H、W、C(通道),所以要在writer.add_image用dataformats转换为H、W、C
总结从PIL到numpy,需在add_image()中指定shape中每一个 数字/维 表示的含义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值