简介
-
TensorBoard,可视化工具
-
原本是tensorflow的可视化工具,pytorch从1.2.0开始支持tensorboard。之前的版本也可以使用tensorboardX代替
-
可视化工具,展示网络图、张量的指标变化、张量的分布
-
TensorBoard运行时开启本地服务器,监听6006端口。在浏览器发出请求时,获取数据并绘制可视化图像
-
主要功能:
(1)Scalars:展示训练过程中的准确率、损失值、权重/偏置的变化情况。
(2)Images:展示训练过程中记录的图像。
(3)Audio:展示训练过程中记录的音频。
(4)Graphs:展示模型的数据流图,以及训练在各个设备上消耗的内存和时间。
(5)Distributions:展示训练过程中记录的数据的分部图。
(6)Histograms:展示训练过程中记录的数据的柱状图。
(7)Embeddings:展示词向量后的投影分部。
使用
准备
- 安装
pip install tensorboard
- 导入
from torch.utils.tensorboard import SummaryWriter
- 命令行使用(环境变量)
tensorboard --logdir=logs
- 端口默认6006,冲突,指定端口
tensorboard --logdir=logs --port 8888
- 指定主机
tensorboard --logdir=logs --host 127.0.0.1
使用步骤
-
使用步骤如下:
-
读取数据并转换
-
设置TensorBoard,设置保存路径
writer = SummaryWriter('logs')
-
写入TensorBoard
-
使用tensorboard检查模型架构
- 跟踪训练模型时表现
- 训练后评估模型的表现
-
使用tensorboard创建可视化的交互式版本
tensorboard --logdir=logs
-
标量可视化
add_scalar(self, tag, scalar_value, global_step=None, walltime=None, new_style=False)
tag
:标签scalar_value
:监测变量的值global_step
:步长索引
writer = SummaryWriter("logs/log_scalar")
for i in range(1, 100):
writer.add_scalar('y=2x', i * 2, i)
writer.close()
图像可视化
add_image(self, tag, img_tensor, global_step=None, walltime=None, dataformats='CHW')
- 支持的图像格式 orch.Tensor, numpy.array
- 默认shape(3, H, W),其余需要指定格式 ,格式是RGB格式
- opencv读取图片
img = cv2.imdecode(np.fromfile(path, dtype='uint8'), -1)
writer.add_image('img_read', img, 0, dataformats='HWC')
- 栅格图像
img_grid = torchvision.utils.make_grid(images)
writer.add_image('four_fashion_mnist_images', img_grid)
模型结构可视化
add_graph
:可视化复杂模型结构
writer.add_graph(net, images)
模型训练监测
-
test_accuracy
-
test_loss
-
train_loss
import torchvision, torch
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64*4*4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model(x)
return x
train_dataset = torchvision.datasets.CIFAR10(
root=r"E:\Data\CIFAR10",
train=True,
download=False,
transform=torchvision.transforms.ToTensor()
)
test_dataset = torchvision.datasets.CIFAR10(
root=r"E:\Data\CIFAR10",
train=False,
transform=torchvision.transforms.ToTensor()
)
train_dataset_size = len(train_dataset)
test_dataset_size = len(test_dataset)
print("训练数据集的长度为:{}".format(train_dataset_size))
print("测试数据集的长度为:{}".format(test_dataset_size))
train_dataloader = DataLoader(train_dataset, batch_size=64)
test_dataloader = DataLoader(test_dataset, batch_size=64)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 创建神经网络
net = Model()
net = net.to(device)
# 损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)
# 优化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(net.parameters(), lr = learning_rate)
# 设置训练网络的一些参数
total_train_step = 0 # 记录训练次数
total_test_step = 0 # 记录测试次数
epoch = 10 # 记录训练轮数
# 添加tensorboard
writer = SummaryWriter("logs")
for i in range(epoch):
print("~~~~~~~~~~~~~~第{}轮训练开始~~~~~~~~~~~~~~~".format(i+1))
# 训练开始
net.train()
for data in train_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = net(imgs)
loss = loss_fn(outputs, targets)
# 优化器优化模型
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_train_step += 1
if total_train_step % 100 == 0:
print("训练次数:{}, loss:{:.3f}".format(total_train_step, loss.item()))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 每次训练完一轮,测试
net.eval()
total_test_loss = 0
total_accuracy = 0
with torch.no_grad():
for data in test_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = net(imgs)
loss = loss_fn(outputs, targets)
total_test_loss += loss
accuracy = (outputs.argmax(1) == targets).sum()
total_accuracy += accuracy
print("测试集上的loss:{}".format(total_test_loss.item()))
writer.add_scalar("test_loss", total_test_loss.item(), total_test_step)
print("整体测试的正确率:{}".format(total_accuracy / test_dataset_size))
writer.add_scalar("test_accuracy", total_accuracy / test_dataset_size, total_test_step)
total_test_step += 1
writer.close()
client获取TensorBoard数据
- 按照Web应用程序,写了个简单client,获取scalar和image数据
- add_scalar
- add_image
class TensorBoardClient:
def __init__(self, host="127.0.0.1", port=6006):
self.host = host
self.port = port
self.baseURL = "http://%s:%d" % (host, port)
self.headers = {"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
"Content-Type": "application/json",
"Accept": "*/*"
}
self.session = requests.session()
def plugins_listing(self):
# 列出所有的插件
url = "%s/data/plugins_listing" % self.baseURL
print(url)
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print('plugins_listing ', response.text)
def environment(self):
# 运行环境
url = "%s/data/environment" % self.baseURL
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print('environment ', response.text)
def experiments(self):
# experiments
url = "%s/data/experiments" % self.baseURL
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print('experiments ', response.text)
return response.json()
def runs(self):
# runs
url = "%s/data/runs" % self.baseURL
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print('runs ', response.text)
runs = response.json()[0]
return runs
def getScalar(self):
# tags
runs = self.runs()
print('runs', runs)
experiment = self.experiments()
print('experiment', experiment)
# 获取scalar的所有的tag
url = "%s/data/plugin/scalars/tags" % self.baseURL
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print('tags ', response.text)
tags = response.json()[runs] # 似乎是runs,返回值
for k, v in tags.items():
# 针对每个tag单独显示内容
print(k, v)
# scalar?tag
url = "%s/data/plugin/scalars/scalars?tag=%s&run=%s&experiment=" % (self.baseURL, k, runs)
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print(response.text)
def _saveImage(self, filePath, response):
size = 0
with open(filePath, "wb") as f: # 文件保存
for chunk in response.iter_content(chunk_size=1024):
size += f.write(chunk)
def _byte2Image(self, byteData):
img = cv2.imdecode(np.frombuffer(byteData, np.uint8), cv2.IMREAD_COLOR)
return img
def showImage(self, wnd_name, img):
cv2.namedWindow(wnd_name, cv2.WINDOW_NORMAL)
cv2.imshow(wnd_name, img)
cv2.waitKey(0)
def getImage(self):
runs = self.runs()
url = "%s/data/plugin/images/tags" % self.baseURL
response = self.session.get(url, headers=self.headers)
print(response.status_code)
print(response.text)
items = response.json()[runs]
for k, v in items.items():
# print(k, v)
url = "%s/data/plugin/images/images?run=%s&sample=%d&tag=%s" % (self.baseURL, runs, 0, k)
response = self.session.get(url, headers=self.headers) # 查询图片
l_img = response.json()
for img in l_img:
query = img['query']
url = "%s/data/plugin/images/individualImage?ts=%s&%s" % (self.baseURL, 1 ,query)
response = self.session.get(url, headers=self.headers) # 查询图片
# filePath = r'%s.jpg' % k
# self._saveImage(filePath, response)
# print(type(response.content))
img = self._byte2Image(response.content)
self.showImage(k, img)
QA
localhost
无法显示
tensorboard --logdir=‘log’ --host=127.0.0.1
- 默认端口6006,端口被占用
tensorboard --logdir=‘log’ --port=6602
- 路径不能有中文
- 多个文件,读取最近一次
- 有界面,无法显示数据,返回`return self._accumulators[run],KeyError: None
更换浏览器为Chrome浏览器,360浏览器,搜狗都不行