PyTorch: CNN实战MNIST手写数字识别

PyTorch: CNN实战MNIST手写数字识别

  • cnn
  • 导包
  • 加载数据
  • 构造CNN
  • 训练并计算损失
  • 结果

cnn

卷积神经网络CNN的结构一般包含这几个层: 
输入层:用于数据的输入 
卷积层:使用卷积核进行特征提取和特征映射 
激励层:由于卷积也是一种线性运算,因此需要增加非线性映射 
池化层:进行下采样,对特征图稀疏处理,减少数据运算量。 
全连接层:通常在CNN的尾部进行重新拟合,减少特征信息的损失 
输出层:用于输出结果

导包

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable

换了一台电脑,这台只装了pytorch,没有装Torchvision,重新安装Torchvision

conda install torchvision
D:\document\ML\camp>conda install torchvision
Fetching package metadata ...............

PackageNotFoundError: Packages missing in current channels:

  - torchvision

找不到相应的package
换官网上安装命令conda install pytorch-cpu torchvision-cpu -c pytorch,报http请求错误

D:\document\ML\camp>conda install pytorch-cpu torchvision-cpu -c pytorch
Fetching package metadata ...
CondaHTTPError: HTTP 000 CONNECTION FAILED for url 
Elapsed: -

删掉中间的pytorch

D:\document\ML\camp>conda install torchvision-cpu -c pytorch
Fetching package metadata .................
Solving package specifications: .

Package plan for installation in environment C:\ProgramData\Anaconda3:

The following NEW packages will be INSTALLED:

    torchvision-cpu: 0.2.2-py_3 pytorch

Proceed ([y]/n)? y

torchvision-cp 100% |###############################| Time: 0:00:01  23.94 kB/s

装好了

加载数据

# MNIST Dataset
train_dataset = datasets.MNIST(root='./data/',
                               train=True,
                               transform=transforms.ToTensor(),
                               download=True)

test_dataset = datasets.MNIST(root='./data/',
                              train=False,
                              transform=transforms.ToTensor())

# Data Loader (Input Pipeline)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)

构造CNN

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 输入1通道,输出10通道,kernel 5*5
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.mp = nn.MaxPool2d(2)
        # fully connect
        self.fc = nn.Linear(320, 10)

    def forward(self, x):
        # in_size = 64
        in_size = x.size(0) # one batch
        # x: 64*10*12*12
        x = F.relu(self.mp(self.conv1(x)))
        # x: 64*20*4*4
        x = F.relu(self.mp(self.conv2(x)))
        # x: 64*320
        x = x.view(in_size, -1) # flatten the tensor
        # x: 64*10
        x = self.fc(x)
        return F.log_softmax(x)


model = Net()

optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

训练并计算损失

def train(epoch):
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = Variable(data), Variable(target)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % 200 == 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()))


def loss():
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data, target = Variable(data, volatile=True), Variable(target)
        output = model(data)
        # sum up batch loss
        test_loss += F.nll_loss(output, target, size_average=False).item()
        # get the index of the max log-probability
        pred = output.data.max(1, keepdim=True)[1]
        correct += pred.eq(target.data.view_as(pred)).cpu().sum()

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


for epoch in range(1, 10):
    train(epoch)
    loss()

结果

最后得到的准确率为98%, loss: 0.0507

Train Epoch: 1 [0/60000 (0%)]	Loss: 2.320769
Train Epoch: 1 [12800/60000 (21%)]	Loss: 0.519038
Train Epoch: 1 [25600/60000 (43%)]	Loss: 0.335463
Train Epoch: 1 [38400/60000 (64%)]	Loss: 0.266052
Train Epoch: 1 [51200/60000 (85%)]	Loss: 0.192065

Test set: Average loss: 0.1718, Accuracy: 9496/10000 (94%)

Train Epoch: 2 [0/60000 (0%)]	Loss: 0.196151
Train Epoch: 2 [12800/60000 (21%)]	Loss: 0.117710
Train Epoch: 2 [25600/60000 (43%)]	Loss: 0.112761
Train Epoch: 2 [38400/60000 (64%)]	Loss: 0.215878
Train Epoch: 2 [51200/60000 (85%)]	Loss: 0.158413

Test set: Average loss: 0.1082, Accuracy: 9683/10000 (96%)

Train Epoch: 3 [0/60000 (0%)]	Loss: 0.140935
Train Epoch: 3 [12800/60000 (21%)]	Loss: 0.135737
Train Epoch: 3 [25600/60000 (43%)]	Loss: 0.092188
Train Epoch: 3 [38400/60000 (64%)]	Loss: 0.084430
Train Epoch: 3 [51200/60000 (85%)]	Loss: 0.077458

Test set: Average loss: 0.0812, Accuracy: 9763/10000 (97%)

Train Epoch: 4 [0/60000 (0%)]	Loss: 0.064760
Train Epoch: 4 [12800/60000 (21%)]	Loss: 0.151439
Train Epoch: 4 [25600/60000 (43%)]	Loss: 0.113604
Train Epoch: 4 [38400/60000 (64%)]	Loss: 0.061374
Train Epoch: 4 [51200/60000 (85%)]	Loss: 0.036855

Test set: Average loss: 0.0656, Accuracy: 9807/10000 (98%)

Train Epoch: 5 [0/60000 (0%)]	Loss: 0.159602
Train Epoch: 5 [12800/60000 (21%)]	Loss: 0.054143
Train Epoch: 5 [25600/60000 (43%)]	Loss: 0.112333
Train Epoch: 5 [38400/60000 (64%)]	Loss: 0.163274
Train Epoch: 5 [51200/60000 (85%)]	Loss: 0.067363

Test set: Average loss: 0.0667, Accuracy: 9796/10000 (97%)

Train Epoch: 6 [0/60000 (0%)]	Loss: 0.092683
Train Epoch: 6 [12800/60000 (21%)]	Loss: 0.111712
Train Epoch: 6 [25600/60000 (43%)]	Loss: 0.053559
Train Epoch: 6 [38400/60000 (64%)]	Loss: 0.033269
Train Epoch: 6 [51200/60000 (85%)]	Loss: 0.048830

Test set: Average loss: 0.0587, Accuracy: 9822/10000 (98%)

Train Epoch: 7 [0/60000 (0%)]	Loss: 0.043137
Train Epoch: 7 [12800/60000 (21%)]	Loss: 0.034103
Train Epoch: 7 [25600/60000 (43%)]	Loss: 0.072622
Train Epoch: 7 [38400/60000 (64%)]	Loss: 0.066607
Train Epoch: 7 [51200/60000 (85%)]	Loss: 0.041002

Test set: Average loss: 0.0544, Accuracy: 9840/10000 (98%)

Train Epoch: 8 [0/60000 (0%)]	Loss: 0.009038
Train Epoch: 8 [12800/60000 (21%)]	Loss: 0.059637
Train Epoch: 8 [25600/60000 (43%)]	Loss: 0.012170
Train Epoch: 8 [38400/60000 (64%)]	Loss: 0.018512
Train Epoch: 8 [51200/60000 (85%)]	Loss: 0.049446

Test set: Average loss: 0.0475, Accuracy: 9846/10000 (98%)

Train Epoch: 9 [0/60000 (0%)]	Loss: 0.016563
Train Epoch: 9 [12800/60000 (21%)]	Loss: 0.068632
Train Epoch: 9 [25600/60000 (43%)]	Loss: 0.027334
Train Epoch: 9 [38400/60000 (64%)]	Loss: 0.032353
Train Epoch: 9 [51200/60000 (85%)]	Loss: 0.021624

Test set: Average loss: 0.0507, Accuracy: 9840/10000 (98%)


Process finished with exit code 0

你可能感兴趣的:(PyTorch)