Visdom 使用教程


visdom安装与启动服务

安装visdom

pip install visdom

打开服务

python -m visdom.server

一直出现下面问题(解决办法:(42条消息) Visdom库(pytorch中的可视化工具)安装问题的解决方案及使用方法详解_Wendy的博客-CSDN博客)

 默认大家已经解决这个问题

 浏览器中打开对应的网址。

visdom常用功能

首先创建一个新的环境,如不创建则默认在main环境下

import numpy as np
import visdom
import time

viz = visdom.Visdom(env="Test1") # 创建环境名为Test1

image窗口:图像显示与更新窗口显示

下面代码在一个image窗口中不断更新显示图像

#单张图像显示与更新demo
image = viz.image(np.random.rand(3,256,256),opts={'title':'image1','caption':'How random.'})
for i in range(10):
    viz.image(np.random.randn( 3, 256, 256),win = image)
    time.sleep(0.5)

相关代码如下:

 刷新Visdom 出现如下界面:

images窗口:多个图像显示与更新窗口显示

#多图像显示与更新demo
images = viz.images(
        np.random.randn(20, 3, 64, 64),
        opts=dict(title='Random images', caption='How random.',nrow=5)
    )
for i in range(10):
    viz.images(np.random.randn(20, 3, 64, 64),win = images)
    time.sleep(0.5) 

Visdom支持图像的批量显示

from visdom import Visdom
import numpy as np
import torch
from torchvision import datasets, transforms

# 注意数据集路径
train_loader = torch.utils.data.DataLoader(datasets.MNIST(
    r'D:\data',
    train=True,
    download=true,
    transform=transforms.Compose(
        [transforms.ToTensor()])),batch_size=128,shuffle=True)
sample=next(iter(train_loader)) # 通过迭代器获取样本
# sample[0]为样本数据 sample[1]为类别  nrow=16表示每行显示16张图像
viz = Visdom(env='my_visual') # 注意此时我已经换了新环境
viz.images(sample[0],nrow=16,win='mnist',opts=dict(title='mnist'))

# 'mnist'

text窗口:显示文本与更新文本

#text 显示与更新显示demo,将在窗口中连续打印字符
text = viz.text('Hello World !')
strForOut = "This is a string for you to print!"
out = ""
for i in range(len(strForOut)):
    out = out + strForOut[i]
    viz.text(out,win = text)
    time.sleep(0.2)

line窗口:绘制折线图与更新折线图

#绘画折线图演示
x=0
name=['acc','loss','loss2']
for i in range(50):
    y = np.random.randint(5, size=(1, 3))
    viz.line(Y=y,X=np.ones(y.shape)*x,
                    win='line',
                    opts=dict(legend=name,
                        title='line test',
                        width=800,
                        height=800,
                        xlabel='Time',
                        ylabel='Volume'),
                    update=None if x == 0 else 'append'
                    )
    time.sleep(0.1)
    x+=1

scatter窗口:绘制散点图与更新散点图

# 绘制散点图演示 二维
colors = np.random.randint(0, 255, (3, 3,))#第一维3表示该数据可以分为三类,以三种颜色的三点来比表示
win = viz.scatter(
    X=np.random.rand(255, 2),#表示要展示的散点数据
    #Y=(np.random.rand(255) + 1.5).astype(int),
    Y=np.random.randint(1,4,(255)),#每一个数据的类别,将以其对应的colors中的颜色来显示
    opts=dict(
        markersize=5,
        markercolor=colors,
        legend=['1', '2','3'],
        markersymbol = 'cross-thin-open'
    ),
)
# 绘制散点图演示 三维
colors = np.random.randint(0, 255, (3, 3,))#第一维3表示该数据可以分为三类,以三种颜色的三点来比表示
win = viz.scatter(
    X=np.random.rand(255, 3),#表示要展示的散点数据
    #Y=(np.random.rand(255) + 1.5).astype(int),
    Y=np.random.randint(1,4,(255)),#每一个数据的类别,将以其对应的colors中的颜色来显示
    opts=dict(
        markersize=5,
        markercolor=colors,
        legend=['1', '2','3'],
        markersymbol = 'cross-thin-open'
    ),
)

#实时更新绘制散点图
legend=['1', '2','3']
Scatter = viz.scatter(
    X=np.array([[0,0]]),
    Y=np.array([1]),
    opts=dict(
        markersize=5,
        legend=legend,
        # markersymbol = 'cross-thin-open'
        ),
    )


for i in range(20):
    X = np.random.rand(1,2)
    Y = np.random.randint(1,4,1)
    print(Y)

    viz.scatter(
        X=X,
        Y=Y,
        win=Scatter,
        update= 'append',
        name = legend[Y[0]-1],
        opts=dict(
            markersize=5,
            # markersymbol = 'cross-thin-open'
            )
    )
    time.sleep(0.5)

 通过具体的训练过程通过visdom可视化,通过具体的训练过程通过visdom可视化

'''
导入库文件
'''
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
import numpy as np


'''
构建简单的模型:简单线性层+Relu函数的多层感知机
'''
class MLP(nn.Module):

    def __init__(self):
        super(MLP, self).__init__()

        self.model = nn.Sequential(
            nn.Linear(784, 200),
            nn.ReLU(inplace=True),
            nn.Linear(200, 200),
            nn.ReLU(inplace=True),
            nn.Linear(200, 10),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = self.model(x)

        return x


batch_size = 128
learning_rate = 0.01
epochs = 10

# 注意数据集路径
train_loader = torch.utils.data.DataLoader(datasets.MNIST(
    r'D:\Users\Administrator\Desktop\PythonDLbasedonPytorch\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(
    r'D:\Users\Administrator\Desktop\PythonDLbasedonPytorch\data',
    train=False,
    transform=transforms.Compose(
        [transforms.ToTensor(),
            transforms.Normalize((0.1307, ), (0.3081, ))])),
                                            batch_size=batch_size,
                                            shuffle=True)

# 注意此处初始化visdom类
viz = Visdom()
# 绘制起点
viz.line([0.], [0.], win="train loss", opts=dict(title='train_loss'))
device = torch.device('cuda:0')
net = MLP().to(device)
optimizer = optim.SGD(net.parameters(), lr=learning_rate)
criteon = nn.CrossEntropyLoss().to(device)

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

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

    test_loss /= len(test_loader.dataset)
    # 绘制epoch以及对应的测试集损失loss
    viz.line([test_loss], [epoch], win="train loss", update='append')
    print(
        '\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
            test_loss, correct, len(test_loader.dataset),
            100. * correct / len(test_loader.dataset)))

loss曲线如图所示

 ..........

visdom基本可视化函数

- vis.image : 图片
- vis.line: 曲线
- vis.images : 图片列表
- vis.text : 抽象HTML 输出文字
- vis.properties : 属性网格
- vis.audio : 音频
- vis.video : 视频
- vis.svg : SVG对象
- vis.matplot : matplotlib图
- vis.save : 序列化状态服务端

上述函数参数

  • 注意opt的参数都可以用python字典的格式传入,大家可以参考下方使用方法
- opts.title : 图标题
- opts.width : 图宽
- opts.height : 图高
- opts.showlegend : 显示图例 (true or false)
- opts.xtype : x轴的类型 ('linear' or 'log')
- opts.xlabel : x轴的标签
- opts.xtick : 显示x轴上的刻度 (boolean)
- opts.xtickmin : 指定x轴上的第一个刻度 (number)
- opts.xtickmax : 指定x轴上的最后一个刻度 (number)
- opts.xtickvals : x轴上刻度的位置(table of numbers)
- opts.xticklabels : 在x轴上标记标签 (table of strings)
- opts.xtickstep : x轴上刻度之间的距离 (number)
- opts.xtickfont :x轴标签的字体 (dict of font information)
- opts.ytype : type of y-axis ('linear' or 'log')
- opts.ylabel : label of y-axis
- opts.ytick : show ticks on y-axis (boolean)
- opts.ytickmin : first tick on y-axis (number)
- opts.ytickmax : last tick on y-axis (number)
- opts.ytickvals : locations of ticks on y-axis (table of numbers)
- opts.yticklabels : ticks labels on y-axis (table of strings)
- opts.ytickstep : distances between ticks on y-axis (number)
- opts.ytickfont : font for y-axis labels (dict of font information)
- opts.marginleft : 左边框 (in pixels)
- opts.marginright :右边框 (in pixels)
- opts.margintop : 上边框 (in pixels)
- opts.marginbottom: 下边框 (in pixels)
- opts.lagent=['']: 显示图标

更多应用请参考官方demo:
https://github.com/facebookresearch/visdom/blob/master/example/demo.py

GitHub地址:https://github.com/facebookresearch/visdom

Ref:(42条消息) visdom 使用教程_加油_加油_DrDu的博客-CSDN博客_visdom使用

  (42条消息) PyTorch 训练可视化教程 visdom_赵继超的笔记-CSDN博客_pytorch训练可视化