【pytorch】tensorboard的使用

一、tensorboard的说明

TensorBoard是深度学习领域通用的可视化工具套件,TensorBoard的核心价值在于将抽象的模型训练过程转化为直观的可视化图表。

在PyTorch中,SummaryWriter是TensorBoard的数据写入器,用于将训练数据(指标、模型结构、图像等)记录到事件文件(event files)中。

python 复制代码
class SummaryWriter(object):
    """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.
    """

记录标量(指标):使用add_scalar方法跟踪损失、准确率等指标。

记录图像:使用add_image方法展示训练数据或生成样本。

二、tensorboard的画图使用

add_scalar:scalar_value是y轴,global_step是x轴

创建y=x和y=2x的图,并通过网页展示

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

writer = SummaryWriter('logs')
# writer.add_image()
for i in range(100):
    writer.add_scalar('y=2x', 2*i, i)

writer.close()

在控制台输出,也可以指定其他端口tensorboard --logdir=logs --port=6007:

powershell 复制代码
tensorboard --logdir=logs

输出

浏览器打开http://localhost:6006/

三、tensorboard的记录图片使用

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

writer = SummaryWriter('logs')
image_path = r'data/train/ants_image/0013035.jpg'
img_PIL = Image.open(image_path)
img_array = np.array(img_PIL)
#img_array的shape是(512, 768, 3),通道3,需要加dataformats='HWC'参数,否则报错
writer.add_image("test", img_array, 1, dataformats='HWC')


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

writer.close()

输出

相关推荐
Studying 开龙wu13 小时前
深度学习PyTorch 实战九:YOLOv1目标检测从标注-训练-预测
pytorch·深度学习·yolo
ting945200017 小时前
动手学深度学习(PyTorch版)深度详解(8):现代循环神经网络(实战 + 避坑)
pytorch·rnn·深度学习
郝学胜-神的一滴18 小时前
二分类任务核心:BCE 损失函数从原理到 PyTorch 实战
人工智能·pytorch·python·算法·机器学习·分类·数据挖掘
T.i.s2 天前
总变差正则化(TV Loss)的思考
人工智能·pytorch·深度学习
盼小辉丶2 天前
PyTorch强化学习实战(4)——PyTorch基础
人工智能·pytorch·python·强化学习
keineahnung23452 天前
為什麼這個 Tensor 算 dense?PyTorch _eval_is_non_overlapping_and_dense 深入解析
人工智能·pytorch·python·深度学习
袋子(PJ)2 天前
2026年pytorch基础学习(基于jupyter notebook开发)——从原理到落地:PyTorch神经网络架构与工程优化解析
人工智能·pytorch·深度学习·学习·jupyter
九成宫2 天前
动手学深度学习PyTorch版初步安装过程
人工智能·pytorch·深度学习
AI技术增长3 天前
Pytorch图像去噪实战(十三):DDIM加速扩散模型采样,让去噪从1000步降到50步
人工智能·pytorch·python
小糖学代码3 天前
LLM系列:1.python入门:16.正则表达式与文本处理 (re)
人工智能·pytorch·python·深度学习·神经网络·正则表达式