赞
踩
导入必要的依赖包:
from pathlib import Path
import glob
import re
import numpy as np
from torch.utils.tensorboard import SummaryWriter
生成文件夹。在指定路径下遍历,以后缀自增的形式创建新的文件夹,避免重复
# https://github.com/ultralytics/yolov5/blob/c1bed601e9b9a3f5fa8fb529cfa40df7a3a0b903/utils/general.py#L805
def increment_path(path, exist_ok=False, sep='', mkdir=False):
# Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
path = Path(path) # os-agnostic
if path.exists() and not exist_ok:
suffix = path.suffix
path = path.with_suffix('')
dirs = glob.glob(f"{path}{sep}*") # similar paths
matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
i = [int(m.groups()[0]) for m in matches if m] # indices
n = max(i) + 1 if i else 2 # increment number
path = Path(f"{path}{sep}{n}{suffix}") # update path
dir = path if path.suffix == '' else path.parent # directory
if not dir.exists() and mkdir:
dir.mkdir(parents=True, exist_ok=True) # make directory
return path
训练并记录:
epochs = 10
steps = 100
save_dir = increment_path('runs1/exp')
print(save_dir)
writer = SummaryWriter(save_dir)
iteration = 0
for epoch in range(epochs):
for step in range(steps):
# train
writer.add_scalar('Loss/train', np.random.random(), iteration)
writer.add_scalar('Accuracy/train', np.random.random(), iteration)
# val
writer.add_scalar('Loss/val', np.random.random(), iteration)
writer.add_scalar('Accuracy/val', np.random.random(), iteration)
iteration += 1
writer.close()
上面代码多次运行之后的结果:
在命令行中运行TensorBoard查看:
tensorboard --logdir=runs1
每运行一次,会创建一个文件夹,左侧蓝色框
代码中add_scalar
的第一个参数,也就是tag,如'Accuracy/train'
和'Accuracy/val'
,相同的tag会把两个图表放在同一个sectionAccuracy
下
不同的文件夹中的相同tag会画在同个图表中,如右侧4个图表的橙色和蓝色曲线
如果是在同一个文件夹中,具有相同tag的则会画到同一条曲线上,因此在训练时,不同参数的训练要放到不同的文件夹中,否则两次训练会首尾相连,但是如果是中断继续训练,则要放到同一个文件夹中,并且横坐标要从上次中断位置继续。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。