在我们完成深度学习项目工程中,很多时候我们自己构建模型结构,或者在学习深度学习算法的时候,由于算法结构过于复杂,很难充分理解模型结构层次
很多时候,我们自己构建完成训练后,需要在通过修改参数来评估模型的好坏,同时还需要对相应的指标进行可视化,这样是不是有些麻烦。
这里以我的项目目录为例
\torchproject
\data
\tensorboard
\events.out.tfevents....
\ten.py
写入器目录为data/tensorboard,项目代码和Tensorboard代码都在ten.py文件中,写入器将相应信息写入到目录中,会生成一个events.out.tfevents…文件。
生成完events文件,就可以打开终端,进入到data目录下运行如下命令
python3 -m tensorboard.main --logdir=“自己的目录”
在运行的响应的内容中点击http://localhost:6006链接。即可进行TensorBoard界面中。
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3,out_channels=32,kernel_size = 3)
self.pool = nn.MaxPool2d(kernel_size = 2,stride = 2)
self.conv2 = nn.Conv2d(in_channels=32,out_channels=64,kernel_size = 5)
self.dropout = nn.Dropout2d(p = 0.1)
self.adaptive_pool = nn.AdaptiveMaxPool2d((1,1))
self.flatten = nn.Flatten()
self.linear1 = nn.Linear(64,32)
self.relu = nn.ReLU()
self.linear2 = nn.Linear(32,1)
self.sigmoid = nn.Sigmoid()
def forward(self,x):
x = self.conv1(x)
x = self.pool(x)
x = self.conv2(x)
x = self.pool(x)
x = self.dropout(x)
x = self.adaptive_pool(x)
x = self.flatten(x)
x = self.linear1(x)
x = self.relu(x)
x = self.linear2(x)
y = self.sigmoid(x)
return y
net = Net()
writer = SummaryWriter('./data/tensorboard')
writer.add_graph(net,input_to_model = torch.rand(1,3,32,32))
writer.close()
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
# f(x) = a*x**2 + b*x + c的最小值
x = torch.tensor(0.0,requires_grad = True) # x需要被求导
a = torch.tensor(1.0)
b = torch.tensor(-2.0)
c = torch.tensor(1.0)
optimizer = torch.optim.SGD(params=[x],lr = 0.01)
def f(x):
result = a*torch.pow(x,2) + b*x + c
return(result)
writer = SummaryWriter('./data/tensorboard')
for i in range(500):
optimizer.zero_grad()
y = f(x)
y.backward()
optimizer.step()
writer.add_scalar("x",x.item(),i) #日志中记录x在第step i 的值
writer.add_scalar("y",y.item(),i) #日志中记录y在第step i 的值
writer.close()
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
# 创建正态分布的张量模拟参数矩阵
def norm(mean,std):
t = std*torch.randn((100,20))+mean
return t
writer = SummaryWriter('./data/tensorboard')
for step,mean in enumerate(range(-10,10,1)):
w = norm(mean,1)
writer.add_histogram("w",w, step)
writer.flush()
writer.close()
import torch
import torchvision
from torch import nn
from torch.utils.data import Dataset,DataLoader
from torchvision import transforms,datasets
transform_train = transforms.Compose([transforms.ToTensor()])
transform_valid = transforms.Compose([transforms.ToTensor()])
ds_train = datasets.ImageFolder("./data/cifar2/train/",transform = transform_train,target_transform= lambda t:torch.tensor([t]).float())
ds_valid = datasets.ImageFolder("./data/cifar2/test/",transform = transform_train,target_transform= lambda t:torch.tensor([t]).float())
dl_train = DataLoader(ds_train,batch_size = 50,shuffle = True,num_workers=3)
dl_valid = DataLoader(ds_valid,batch_size = 50,shuffle = True,num_workers=3)
dl_train_iter = iter(dl_train)
images, labels = dl_train_iter.next()
# 仅查看一张图片
writer = SummaryWriter('./data/tensorboard')
writer.add_image('images[0]', images[0])
writer.close()
# 将多张图片拼接成一张图片,中间用黑色网格分割
writer = SummaryWriter('./data/tensorboard')
# create grid of images
img_grid = torchvision.utils.make_grid(images)
writer.add_image('image_grid', img_grid)
writer.close()
# 将多张图片直接写入
writer = SummaryWriter('./data/tensorboard')
writer.add_images("images",images,global_step = 0)
writer.close()
import torch
import torchvision
from torch import nn
from torch.utils.data import Dataset,DataLoader
from torchvision import transforms,datasets
transform_train = transforms.Compose([transforms.ToTensor()])
transform_valid = transforms.Compose([transforms.ToTensor()])
ds_train = datasets.ImageFolder("./data/cifar2/train/",transform = transform_train,target_transform= lambda t:torch.tensor([t]).float())
ds_valid = datasets.ImageFolder("./data/cifar2/test/",transform = transform_train,target_transform= lambda
t:torch.tensor([t]).float())
from matplotlib import pyplot as plt
figure = plt.figure(figsize=(8,8))
for i in range(9):
img,label = ds_train[i]
img = img.permute(1,2,0)
ax=plt.subplot(3,3,i+1)
ax.imshow(img.numpy())
ax.set_title("label = %d"%label.item())
ax.set_xticks([])
ax.set_yticks([])
writer = SummaryWriter('./data/tensorboard')
writer.add_figure('figure',figure,global_step=0)
writer.close()
简单实现一个实例
import numpy as np
# SummaryWriter用来创建一个writer,可以记录我们想要可视化的数据。
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('data/tensorboard')
for x in range(100):
# 曲线名称,y轴,x轴
writer.add_scalar('y=2x', x * 2, x)
writer.add_scalar('y=pow(2, x)', 2 ** x, x)
writer.add_scalars('data/scalar_group', {"xsinx": x * np.sin(x),
"xcosx": x * np.cos(x),
"arctanx": np.arctan(x)}, x)
writer.close()
第一部分(1):
1.SCALARS表示我们记录的数据的类型
2.下面的图片表示我们还可以记录的数据类型有那些
下拉后可以看到具体可以记录哪些类型的
4.设置多长时间来读取eventfile,在模型训练的时候我们可以实时的监控模型的变化
第二部分(2):
show data download links 前面如果打勾表示:我们可以将data数据下载下来,下载的结果为csv表格。
表示是否忽略离群点,如果右边一幅图数据点并没有绘制完成,当我们取消勾选,我们就会发现我们的曲线就是完整的曲线。
选择排序方法的功能,如果我们一张图有多条曲线,那么下面的黑框就会把这些曲线对应的值显示出来,这一功能会调整值排序的方式,默认default。
表示我们X轴的设置,
Horizontal Axis
表示横轴:
STEP
表示原始数据作为横轴,RELATIVE
和WALL
都是以时间作为横轴,单位是小时,RELATIVE
是相对时间,WALL
是绝对时间。
第三部分(3):
runs显示所有的 event file,可以选择展示某些 event file 的图像,其中正方形按钮是多选,圆形按钮是单选