pytorch学习(十九)—Visdom可视化训练过程

前言

在训练CNN网络时候,如何实时显示训练过程的数据,比如Loss, Accuracy等, 将这些数据可视化显示有助于我们进行模型调参,模型改进优化。本章节内容将基于visdom可视化工具绘制训练过程的Loss, Acc曲线。

关于visdom的基本用法,请参考之前系列的文章。


开发/测试环境

  • Ubuntu 18.04
  • Anaconda3
  • pycharm
  • visdom
  • pytorch

目的

  • 使用MNIST手写体数据集训练LeNet-5网络
  • 使用visdom实时可视化训练的Loss,Accuracy曲线

过程

定义CNN网络

直接使用pytorch官网的例子(做一次代码搬运工)
网络输入: N x 1 x 32 x 32 (N表示min_batch size)
网络输出: N x 1 x 10 (10个类别)

  • 代码
    net.py
import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

准备数据集

  • 训练集
  • 验证集
    使用torchvision提供的MNIST数据集,不用提前下载。
    注意地方: MNIST数据的图像为28 x 28 x1, 但是定义的网络输入的N x 1 x 32 x 32, 因此对数据进行了Resize((32, 32))
mport torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import visdom
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import net
import utils


dataset_dir = '/media/weipenghui/Extra/MNIST'
transform = transforms.Compose([transforms.Resize((32, 32)),
                                transforms.ToTensor()])
batch_size = 64

train_dataset = torchvision.datasets.MNIST(root=dataset_dir, train=True, transform=transform)
val_dataset = torchvision.datasets.MNIST(root=dataset_dir, train=False, transform=transform)

print('train dataset: {} \nval dataset: {}'.format(len(train_dataset), len(val_dataset)))

train_dataloader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
val_dataloader = DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=False, num_workers=4)

# 显示一个batch
viz = visdom.Visdom(env='train-mnist')
viz.image(torchvision.utils.make_grid(next(iter(train_dataloader))[0], nrow=8), win='train-image')

plt.figure()
utils.imshow(next(iter(train_dataloader)))
plt.show()

matplotlib显示效果:


image.png

visdom显示效果:


image.png

训练网络,可视化Loss,Accuracy

Loss, Accuracy的统计:
batch_size设置为64, 迭代一次即跑完64张图像。本人设置每迭代200次统计一次Train Loss, 并且进行一次完整的测试,分别统计Train Acc, Val Acc, 然后将数据发送给visdom服务端,实时显示。

# ------------------模型,优化方法------------------------------

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
net = net.Net()
net.to(device)
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5)
loss_fc = nn.CrossEntropyLoss()

# -----------------训练---------------------------------------
loss_win = viz.line(np.arange(10))
acc_win = viz.line(X=np.column_stack((np.array(0), np.array(0))),
                   Y=np.column_stack((np.array(0), np.array(0))))
iter_count = 0
for epoch in range(20):

    running_loss = 0.0
    tr_loss = 0.0
    tr_acc = 0.0
    ts_acc = 0.0
    tr_total = 0
    tr_correct = 0
    ts_total = 0
    ts_correct = 0


    scheduler.step()
    for i, sample_batch in enumerate(train_dataloader):
        inputs = sample_batch[0].to(device)
        labels = sample_batch[1].to(device)

        net.train()
        optimizer.zero_grad()

        outputs = net(inputs)

        loss = loss_fc(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        tr_total += labels.size(0)
        tr_correct += (torch.max(outputs, 1)[1] == labels).sum().item()

        if i % 200 == 199:
            # test
            for sample_batch in val_dataloader:
                inputs = sample_batch[0].to(device)
                labels = sample_batch[1].to(device)

                net.eval()
                outputs = net(inputs)

                _, prediction = torch.max(outputs, 1)
                ts_correct += (prediction == labels).sum().item()
                ts_total += labels.size(0)

            tr_loss = running_loss / 200
            tr_acc = tr_correct / tr_total
            ts_acc = ts_correct / ts_total
            iter_count += 200
            if iter_count == 200:
                viz.line(Y=np.array([tr_loss]), X=np.array([iter_count]), update='replace', win=loss_win)
                viz.line(Y=np.column_stack((np.array([tr_acc]), np.array([ts_acc]))),
                         X=np.column_stack((np.array([iter_count]), np.array([iter_count]))),
                         win=acc_win, update='replace',
                         opts=dict(legned=['Train_acc', 'Val_acc']))

            else:
                viz.line(Y=np.array([tr_loss]), X=np.array([iter_count]), update='append', win=loss_win)
                viz.line(Y=np.column_stack((np.array([tr_acc]), np.array([ts_acc]))),
                         X=np.column_stack((np.array([iter_count]), np.array([iter_count]))),
                         win=acc_win, update='append')

            running_loss = 0
            tr_total = 0
            tr_correct = 0
            ts_total = 0
            ts_correct = 0

print('Train finish!')
torch.save(net.state_dict(), './model/model_10_2_epoch.pth')

训练输出

  • Train loss

  • Train acc

  • Val acc

  • mini_batch图像

image.png
Train Loss
Train Val accuracy

最终,验证集的Accuracy达到98%以上。


完整工程

  • train.py
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import visdom
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import net
import utils


dataset_dir = '/media/weipenghui/Extra/MNIST'
transform = transforms.Compose([transforms.Resize((32, 32)),
                                transforms.ToTensor()])
batch_size = 64

train_dataset = torchvision.datasets.MNIST(root=dataset_dir, train=True, transform=transform)
val_dataset = torchvision.datasets.MNIST(root=dataset_dir, train=False, transform=transform)

print('train dataset: {} \nval dataset: {}'.format(len(train_dataset), len(val_dataset)))

train_dataloader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
val_dataloader = DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=False, num_workers=4)

# 显示一个batch
viz = visdom.Visdom(env='train-mnist')
viz.image(torchvision.utils.make_grid(next(iter(train_dataloader))[0], nrow=8), win='train-image')

# plt.figure()
# utils.imshow(next(iter(train_dataloader)))
# plt.show()

# ------------------模型,优化方法------------------------------

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
net = net.Net()
net.to(device)
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5)
loss_fc = nn.CrossEntropyLoss()

# -----------------训练---------------------------------------
loss_win = viz.line(np.arange(10))
acc_win = viz.line(X=np.column_stack((np.array(0), np.array(0))),
                   Y=np.column_stack((np.array(0), np.array(0))))
iter_count = 0
for epoch in range(20):

    running_loss = 0.0
    tr_loss = 0.0
    tr_acc = 0.0
    ts_acc = 0.0
    tr_total = 0
    tr_correct = 0
    ts_total = 0
    ts_correct = 0


    scheduler.step()
    for i, sample_batch in enumerate(train_dataloader):
        inputs = sample_batch[0].to(device)
        labels = sample_batch[1].to(device)

        net.train()
        optimizer.zero_grad()

        outputs = net(inputs)

        loss = loss_fc(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        tr_total += labels.size(0)
        tr_correct += (torch.max(outputs, 1)[1] == labels).sum().item()

        if i % 200 == 199:
            # test
            for sample_batch in val_dataloader:
                inputs = sample_batch[0].to(device)
                labels = sample_batch[1].to(device)

                net.eval()
                outputs = net(inputs)

                _, prediction = torch.max(outputs, 1)
                ts_correct += (prediction == labels).sum().item()
                ts_total += labels.size(0)

            tr_loss = running_loss / 200
            tr_acc = tr_correct / tr_total
            ts_acc = ts_correct / ts_total
            iter_count += 200
            if iter_count == 200:
                viz.line(Y=np.array([tr_loss]), X=np.array([iter_count]), update='replace', win=loss_win)
                viz.line(Y=np.column_stack((np.array([tr_acc]), np.array([ts_acc]))),
                         X=np.column_stack((np.array([iter_count]), np.array([iter_count]))),
                         win=acc_win, update='replace',
                         opts=dict(legned=['Train_acc', 'Val_acc']))

            else:
                viz.line(Y=np.array([tr_loss]), X=np.array([iter_count]), update='append', win=loss_win)
                viz.line(Y=np.column_stack((np.array([tr_acc]), np.array([ts_acc]))),
                         X=np.column_stack((np.array([iter_count]), np.array([iter_count]))),
                         win=acc_win, update='append')

            running_loss = 0
            tr_total = 0
            tr_correct = 0
            ts_total = 0
            ts_correct = 0

print('Train finish!')
torch.save(net.state_dict(), './model/model_10_2_epoch.pth')
  • net.py
import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

  • utils.py
import numpy as np
import torch
from torchvision.utils import make_grid
import matplotlib.pyplot as plt


def imshow(sample_batch):
    inputs, labels = sample_batch
    images_transformed = make_grid(inputs, nrow=4, pad_value=255)
    images_transformed = np.transpose(images_transformed.numpy(), (1, 2, 0))
    plt.imshow(images_transformed)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容