欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

visdom——数据可视化

程序员文章站 2022-05-21 12:22:30
目录1. 安装visdom1. 安装visdomwin+R打开运行,键入:pip install visdom打开使用,键入:python -m visdom.server然后我电脑直接报错就打不开visdom,然后我尝试键入:visdom成功打开把生成的网页 http://localhost:8097复制到浏览器上打开,会出现一个蓝色的屏。运行代码:import torchimport torch.nn as nnimport torch.nn.functional a...

安装visdom
win+R打开运行,键入:

pip install visdom

visdom——数据可视化
打开使用,键入:

python -m visdom.server

然后我电脑直接报错就打不开visdom,然后我尝试键入:

visdom

成功打开
visdom——数据可视化
把生成的网页 http://localhost:8097复制到浏览器上打开,会出现一个蓝色的屏。

from visdom import Visdom
#生成一个viz的环境
viz = Visdom()

#初始化两个小的窗格,来分别绘制train,test的情况
# 绘制初始点,原点
viz.line([0.], [0.], win='train_loss',opts=dict(title='train loss'))  #single-line
viz.line([loss.item()], [global_step], win='trian_loss', update='append')
viz.line([[0., 0.]], [0.], win='test',opts=dict(title='train loss',  legend=['loss', 'acc.']))
viz.line([[test_loss, correct / len(test_loader.dataset)]], [global_step], win='test', update='append')
#这里前两个参数,一个表示指定变化指标数量,一个或者两个提前占位,并初始化为0,
#第二个参数表示进行到第几步全局minibatch批次号总共进行了几个minibatch

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()
		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)))

visdom——数据可视化

本文地址:https://blog.csdn.net/qq_37369201/article/details/107169307