首页人工智能Pytorch16.使用Visdom可视...

16.使用Visdom可视化

使用Tensorflow就会非常熟悉可视化工具tensorboard,通过实时变化的曲线可以查看整个模型的架构等内容。

在PyTorch中,可以通过pip install tensorboardX安装使用tensorboardX工具,该工具完全借鉴Tensorflow的tensorboard,不过因为pytorch是动态图,因此使用tensorboardX时跟Tensorflow会有一些不太一样。

相比tensorboardX,Visdom工具更简洁方便(例如对image数据的可视化可以直接使用Tensor,而不必转到cpu上再转为numpy数据),刷新率也更快。

1.安装Visdom:

使用pip install visdom就可以很方便快捷的完成工具安装。
在程序运行之前需要开启一个监听进程,使用python -m visdom.server即可完成。

但是有时在windows上会有错误,这些先从Github上下载Visdom的源码。
下载完成后进入解压后的目录,执行:pip install -e .命令。
安装完成后,执行python -m visdom.server命令,开启监听。

在浏览器中打开http://localhost:8097/就可以看到如下界面,表示运行成功。

2.可视化MNIST数据集训练过程:

import torch
import torch.nn as nn
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)))

打开http://localhost:8097/可以看到可视化信息如下:

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments