Visdom 总结

1. 远程映射

$ python -m visdom.server

# 可选参数
# -port:运行服务器的端口(默认8097)
# -env_path:重新加载序列化会话的路径
# -logging_level:记录级别(默认=INFO)。接受标准文本和数字记录值

如果不起作用,请将以下行添加到本地

~/.ssh/config:LocalForward 127.0.0.1:8097 127.0.0.1:8097

2. python 用法

import visdom
import torch
import numpy as np
# ------ 指定environment ------
vis = visdom.Visdom(env='test')

# --------- vis.line ---------
x = torch.arange(0, 10, 0.01)
y = torch.sin(x)
vis.line(X=x, Y=y, win='sinx', opts={'title': 'y=sin(x)'})

# ------ update中的append ------
for i in range(10):
    x = torch.Tensor([i])
    y = x**2
    vis.line(X=x,Y=y, win='sinx', update='append')

# ----------- image -----------
vis.image(np.random.randn(3, 64, 64), win='image')

# ----------- images -----------
vis.images(np.random.randn(32, 3, 64, 64), nrow=8, win='images')

# ----------- heatmap -----------
viz.heatmap(
    X=np.outer(np.arange(1, 6), np.arange(1, 11)),
    opts=dict(
        columnnames=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
        rownames=['y1', 'y2', 'y3', 'y4', 'y5'],
        colormap='Electric',
    )
)

3. Example 1

Project: pytorch-semseg Author: meetshah1995 File: train.py

def train(args):

    # Setup Dataloader
    data_loader = get_loader(args.dataset)
    data_path = get_data_path(args.dataset)
    loader = data_loader(data_path, is_transform=True, img_size=(args.img_rows, args.img_cols))
    n_classes = loader.n_classes
    trainloader = data.DataLoader(loader, batch_size=args.batch_size, num_workers=4, shuffle=True)

    # Setup visdom for visualization
    if args.visdom:
        vis = visdom.Visdom()

        loss_window = vis.line(X=torch.zeros((1,)).cpu(),
                           Y=torch.zeros((1)).cpu(),
                           opts=dict(xlabel='minibatches',
                                     ylabel='Loss',
                                     title='Training Loss',
                                     legend=['Loss']))

    # Setup Model
    model = get_model(args.arch, n_classes)

    model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))
    model.cuda()
    optimizer = torch.optim.SGD(model.parameters(), lr=args.l_rate, momentum=0.99, weight_decay=5e-4)

    for epoch in range(args.n_epoch):
        for i, (images, labels) in enumerate(trainloader):
            images = Variable(images.cuda())
            labels = Variable(labels.cuda())

            optimizer.zero_grad()
            outputs = model(images)

            loss = cross_entropy2d(outputs, labels)

            loss.backward()
            optimizer.step()

            if args.visdom:
                vis.line(
                    X=torch.ones((1, 1)).cpu() * i,
                    Y=torch.Tensor([loss.data[0]]).unsqueeze(0).cpu(),
                    win=loss_window,
                    update='append')

            if (i+1) % 20 == 0:
                print("Epoch [%d/%d] Loss: %.4f" % (epoch+1, args.n_epoch, loss.data[0]))

        torch.save(model, "{}_{}_{}_{}.pkl".format(args.arch, args.dataset, args.feature_scale, epoch))
Table of Contents