MNIST初体验

utils.py代码

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import matplotlib.pyplot as plt
import torch
def plot_curve(data):
    fig = plt.figure()
    plt.plot(range(len(data)),data,color = 'blue')
    plt.legend(['value'],loc = 'upper right')
    plt.xlabel('step')
    plt.ylabel('value')
    plt.show()

def plot_image(img, label, name):
    fig = plt.figure()
    for i in range(6):
        plt.subplot(2, 3, i + 1)
        plt.tight_layout()
        plt.imshow(img[i][0] * 0.3081 + 0.1307, cmap='gray', interpolation='none')
        plt.title("{}:{}".format(name, label[i].item()))
        plt.xticks([])
        plt.yticks([])
    plt.show()

def one_hot(label,depth=10):
    out = torch.zeros(label.size(0),depth)
    idx = torch.LongTensor(label).view(-1,1)
    out.scatter_(dim = 1,index = idx,value = 1)
    return out

算法代码


import torch
import torchvision
import torch.nn as nn
from torch.nn import functional as F
from torch import optim
from utils import one_hot, plot_image
from visdom import Visdom

batch_size = 512
viz = Visdom()
viz.line([0.], [0.], win='train_loss', opts=dict(title='train_loss'))

train_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist.data', train=True, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,)
                                   )
                               ])),
    batch_size=batch_size, shuffle=True)  # shuffle加载时随机打散

test_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist.data', train=False, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,)
                                   )
                               ])),
    batch_size=batch_size, shuffle=True)  # shuffle加载时随机打散


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 256)
        self.fc2 = nn.Linear(256, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(x.size(0), 28 * 28)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        # 第三层可不用激活函数
        return x


net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
global_step = 0
for epoch in range(3):
    for batch_idx, (x, y) in enumerate(train_loader):
        y = one_hot(y)
        out = net(x)
        loss = F.mse_loss(y, out)
        # 也可以使用cross_entropy_loss
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        viz.line([loss.item()], [global_step], win='train_loss', update='append')
        global_step += 1

x, y = next(iter(test_loader))
out = net(x)
pred = out.argmax(dim=1)
plot_image(x, pred, 'test')


你可能感兴趣的:(python,深度学习)