使用pip install tensorboardX
命令来安装。
tensorboardX在pytorch中怎么使用:
它有一个SummaryWriter,新建一个SummaryWriter实例,把要监听的数据起一个名字,(‘data/scalar’(名字),dummy_s1[0](数据),n_iter(x坐标,代表的是哪一个epoch))。
tensorboard本质上抽取的是一个numpy的数据,如果要和tensor做一个match的话,必须先把tensor转换到cpu上面(.cpu()),然后再转化成numpy数据(data.numpy()),才能够赋值给tensorboard。
from tensorboardX import SummaryWriter
writer=SummaryWriter()
writer.add_scalar('data/scalar',dummy_s1[0],n_iter)
writer.add_scalar('data/scalar_group',{'xsinx':n_iter*np.sin(n_iter),
'xcosx':n_iter*np.cos(n_iter),
'arctanx':np.arctan(n_iter),},n_iter)
writer.add_image('Image',x,n_iter)
writer.add_text('Text','text logged at step:'+str(n_iter),n_iter)
for name,param in resnet18.named_parampython -m visdom.servereters():
writer.add_histogram(name,param.clone().cpu().data.numpy(),n_iter)
writer.close()
使用pip install visdom
命令来安装。安装完成后开启监听的进程,确保程序运行前开启visdom,使用python -m visdom.server
来开启。
windows开启时容易出现错误:
解决这个错误的方法就是重新安装visdom。首先pip uninstall visdom
卸载之前的visdom,然后从官方网页上下载源代码,解压,然后进入到那个目录下面去cd 目录名
,再进入cd visdom-master
,然后pip install -e.
。安装完成之后退回cd ../..
,再python -m visdom.server
。出现监听命令然后复制地址打开浏览器就行了。
地址:http://localhost:8097
展示一个最常见的功能,画一个曲线。
首先创建一个Visdom实例(viz=Visdom()
),再创建一条直线,然后把当前的数据添加到直线上面去,创建一条直线的指令(viz.line([0.](y初始值),[0.](x初始值),win='train_loss'(唯一的标志符,可以理解为ID,创建一个小窗口),opts=dict(title='train loss'(命名)))
)和添加数据指令(viz.line([loss.item()](对于非image数据,传入的还是numpy),[global_step](x坐标),win='train_loss',update='append'(指定update操作,添加到当前直线后面,不指定的话会全部覆盖掉。))
)一定要配合起来使用。
from visdom import Visdom
viz=Visdom()
viz.line([0.],[0.],win='train_loss',opts=dict(title='train loss'))
viz.line([loss.item()],[global_step],win='train_loss',update='append')
我把loss.item()改为1,把global_step改为1,出现此图
多条曲线
创建[y1,y2],legend是一个标识符,代表y1,y2的label。
from visdom import Visdom
viz=Visdom()
viz.line([[0.0,0.0]],[0.],win='test',opts=dict(title='test loss&acc.',
legend=['loss','acc.']))
viz.line([[test_loss,coorrect/len(test_loader.dataset)]],
[global_step],win='test',update='append')
自己添加一些数据,viz.line([[1.0,0.5]],[10],win='test',update='append')
在visdom中传入照片可以直接输入tensor。
from visdom import Visdom
viz=Visdom()
viz.images(data.view(-1,1,28,28),win='x')
viz.text(str(pred.detach().cpu().numpy()),win='pred',
opts=dict(title='pred'))
下面复制完整代码及结果图
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from visdom import Visdom
batch_size=200
learning_rate=0.01
epochs=10
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
# transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
# transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.model = nn.Sequential(
nn.Linear(784, 200),
nn.LeakyReLU(inplace=True),
nn.Linear(200, 200),
nn.LeakyReLU(inplace=True),
nn.Linear(200, 10),
nn.LeakyReLU(inplace=True),
)
def forward(self, x):
x = self.model(x)
return x
device = torch.device('cuda:0')
net = MLP().to(device)
optimizer = optim.SGD(net.parameters(), lr=learning_rate)
criteon = nn.CrossEntropyLoss().to(device)
viz = Visdom()
viz.line([0.], [0.], win='train_loss', opts=dict(title='train loss'))
viz.line([[0.0, 0.0]], [0.], win='test', opts=dict(title='test loss&acc.',
legend=['loss', 'acc.']))
global_step = 0
for epoch in range(epochs):
for batch_idx, (data, target) in enumerate(train_loader):
data = data.view(-1, 28*28)
data, target = data.to(device), target.cuda()
logits = net(data)
loss = criteon(logits, target)
optimizer.zero_grad()
loss.backward()
# print(w1.grad.norm(), w2.grad.norm())
optimizer.step()
global_step += 1
viz.line([loss.item()], [global_step], win='train_loss', update='append')
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
test_loss = 0
correct = 0
for data, target in test_loader:
data = data.view(-1, 28 * 28)
data, target = data.to(device), target.cuda()
logits = net(data)
test_loss += criteon(logits, target).item()
pred = logits.argmax(dim=1)
correct += pred.eq(target).float().sum().item()
viz.line([[test_loss, correct / len(test_loader.dataset)]],
[global_step], win='test', update='append')
viz.images(data.view(-1, 1, 28, 28), win='x')
viz.text(str(pred.detach().cpu().numpy()), win='pred',
opts=dict(title='pred'))
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))