pytorch练习实例——手写数字识别(CNN网络+MNIST数据集)

看到例子时想实现一下几点(基于能把原例子跑出来):
(实现,测试集准确率99%左右)
1,用自己的数据测试模型;(实现,目前只试过0~9,所以不知道准确率)
2,改变网络,获得结果; (实现,了解cnn网络结构,改变stride,padding,kernel_size,网络层数等)
3,获得更好的测试精度;(暂时没有,一般98.3%左右)
4,可视化训练过程;(推荐是说用Tensorboard,先放着)

训练数据得到模型:
VScode运行:途中还遇到一个小问题,有些torch内的模块无法导入,解决方法:

#VSCode中pytorch出现'torch' has no member 'xxx'的错误
https://blog.csdn.net/qq_34403736/article/details/84726504
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

# Hyper parameters
num_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001

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

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

# Data loader
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)


# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc = nn.Linear(7 * 7 * 32, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))

# Test the model
model.eval()  # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

用训练好的模型进行测试

import torch
from PIL import Image
import torch.nn as nn
import torchvision
import matplotlib.pyplot as plt
from torchvision import transforms
import numpy as np
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc = nn.Linear(7 * 7 * 32, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

def test_mydata():
    #调整图片大小
    im = plt.imread('8.png')
    images = Image.open('8.png')
    images = images.resize((28,28))
    images = images.convert('L')

    transform = transforms.ToTensor()
    images = transform(images)
    images = images.resize(1,1,28,28)

    #加在网络和参数
    model = ConvNet()
    model.load_state_dict(torch.load('model.ckpt'))
    model.eval()
    outputs = model(images)
    
    values,indices=outputs.data.max(1)
    plt.title('{}'.format(int(indices[0])))
    plt.imshow(im)
    plt.show()

def test_MNISTdata():
    test_set = torchvision.datasets.MNIST(
    root='data/'#数据文件位置
    ,train=False
    ,download=False
    ,transform=transforms.Compose([
        transforms.ToTensor()
    ])
)
    test_loader = torch.utils.data.DataLoader(
        test_set, batch_size=10
    )
    batch = next(iter(test_loader))
    #加载网络和参数
    images, labels = batch
    model = ConvNet()
    model.load_state_dict(torch.load('model.ckpt'))
    model.eval()
    outputs = model(images)
    grid = torchvision.utils.make_grid(images,nrow=10)#make_grid的作用是将若干幅图像拼成一幅图像。
    plt.imshow(np.transpose(grid,(1,2,0)))#转置,调整图片显示
    values,indices=outputs.data.max(1)
    plt.title('{}'.format(indices))
    plt.show()

test_mydata()

自己修改cnn网络
先了解cnn
参考博客:

https://blog.csdn.net/weixin_34344403/article/details/91689617
https://blog.csdn.net/liufanghuangdi/article/details/81188563
https://zhuanlan.zhihu.com/p/33841176

ok,睡觉,学无止境,继续加油!

你可能感兴趣的:(计算机视觉)