关于手写数字MINIST数据集识别的究极完整版

import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch import nn
import numpy as np
import scipy.ndimage
import time
import math
import csv
import os
import matplotlib.pyplot as plt

batch_size = 64
class DiabetesDataset(Dataset):
    def __init__(self, filepath,UseRotation = False):
        xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
        #self.len = xy.shape[0]
        self.x_data = torch.from_numpy(xy[:, 1:])
        if UseRotation:
            #加上左右旋转10度的图片数据
            self.x_data_plus10 = self.x_data
            for i, x in enumerate(self.x_data_plus10, 0):
                x1 = scipy.ndimage.interpolation.rotate(x.reshape(28, 28), 10, cval=0.0,
                                                        reshape=False).reshape(784)
                self.x_data_plus10[i] = torch.from_numpy(x1)
            self.x_data_minus10 = self.x_data
            for i, x in enumerate(self.x_data_minus10, 0):
                x1 = scipy.ndimage.interpolation.rotate(x.reshape(28, 28), -10, cval=0.0,
                                                        reshape=False).reshape(784)
                self.x_data_minus10[i] = torch.from_numpy(x1)
            self.x_data = torch.cat([self.x_data, self.x_data_plus10, self.x_data_minus10], dim=0)

        self.x_data = (self.x_data/255 - 0.1307)/0.3081    #映射到(0,1)分布,很多时候可以加快收敛速度
        print("x_data.shape = ",self.x_data.shape)
        self.x_data = self.x_data.reshape(-1,1,28,28)  #如果使用CNN需要加上这一句,DNN则注释掉
        self.y_data = torch.from_numpy(xy[:, [0]])
        self.y_data = self.y_data.squeeze(1).long()
        if UseRotation:
            self.y_data = torch.tile(self.y_data, [3])
        print("y_data.shape = ",self.y_data.shape)

    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]


    def __len__(self):
        return len(self.x_data)


train_dataset = DiabetesDataset('mnist_train.csv',UseRotation=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = DiabetesDataset('mnist_test.csv')
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)


class InceptionA(torch.nn.Module):
    def __init__(self, in_channels):
        super(InceptionA, self).__init__()
        self.branch1x1 = nn.Conv2d(in_channels, 16, kernel_size=1)

        self.branch5x5_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch5x5_2 = nn.Conv2d(16, 24, kernel_size=5, padding=2)

        self.branch3x3_1 = nn.Conv2d(in_channels, 16, kernel_size=1)
        self.branch3x3_2 = nn.Conv2d(16, 24, kernel_size=3, padding=1)
        self.branch3x3_3 = nn.Conv2d(24, 24, kernel_size=3, padding=1)

        self.branch_pool = nn.Conv2d(in_channels, 24, kernel_size=1)

    def forward(self, x):
        branch1x1 = self.branch1x1(x)

        branch5x5 = self.branch5x5_1(x)
        branch5x5 = self.branch5x5_2(branch5x5)

        branch3x3 = self.branch3x3_1(x)
        branch3x3 = self.branch3x3_2(branch3x3)
        branch3x3 = self.branch3x3_3(branch3x3)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch5x5, branch3x3, branch_pool]
        return torch.cat(outputs, dim=1)

class ResidualBlock(nn.Module):
    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.channels = channels
        self.conv1 = torch.nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.conv2 = torch.nn.Conv2d(channels, channels, kernel_size=3, padding=1)

    def forward(self, x):
        y = F.relu(self.conv1(x))
        y = self.conv2(y)
        return F.relu(x + y)
#全连接网络
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.l1 = torch.nn.Linear(784, 512)
        self.l2 = torch.nn.Linear(512, 256)
        self.l3 = torch.nn.Linear(256, 128)
        self.l4 = torch.nn.Linear(128, 64)
        self.l5 = torch.nn.Linear(64, 10)
        self.sigmoid = torch.nn.Sigmoid()

    def forward(self, x):
        x = x.view(-1, 784)
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))
        return self.l5(x)
#卷积神经网络
class Net2(torch.nn.Module):
    def __init__(self):
        super(Net2, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10,kernel_size = 5)
        self.conv2 = torch.nn.Conv2d(10, 20,kernel_size = 5)
        self.pooling = torch.nn.MaxPool2d(2)
        self.l1 = torch.nn.Linear(320, 256)
        self.l2 = torch.nn.Linear(256, 128)
        self.l3 = torch.nn.Linear(128, 64)
        self.l4 = torch.nn.Linear(64, 10)

    def forward(self, x):
        #这里拿出第1维的个数即(n,1,28,28)中的第一个元素,是样本一个batch的样本个数
        #注意输入数据是四维的
        batch_size = x.size(0)
        x = F.relu(self.pooling(self.conv1(x)))
        x = F.relu(self.pooling(self.conv2(x)))
        #把它变成全连接网络batch * 320
        x = x.view(batch_size,-1)
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = self.l4(x)
        return x
#inception网络
class Net3(torch.nn.Module):
    def __init__(self):
        super(Net3, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(88, 20, kernel_size=5)
        self.incep1 = InceptionA(in_channels=10)
        self.incep2 = InceptionA(in_channels=20)

        self.mp = nn.MaxPool2d(2)
        self.fc = torch.nn.Linear(1408, 10)
        self.l1 = torch.nn.Linear(1408, 512)
        self.l2 = torch.nn.Linear(512, 128)
        self.l3 = torch.nn.Linear(128, 64)
        self.l4 = torch.nn.Linear(64, 10)

    def forward(self, x):
        in_size = x.size(0)
        # 变成10*12*12
        x = F.relu(self.mp(self.conv1(x)))
        # 变成88*12*12
        x = self.incep1(x)
        # 变成20*4*4
        x = F.relu(self.mp(self.conv2(x)))
        # 变成88*4*4
        x = self.incep2(x)
        # 展开成全连接层
        x = x.view(in_size, -1)
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = self.l4(x)

        return x

#深度残差网络(ResNet)(四个网络中效果最好)
class Net4(torch.nn.Module):
    def __init__(self):
        super(Net4, self).__init__()
        self.conv1 = torch.nn.Conv2d(1, 16, kernel_size=5)
        self.conv2 = torch.nn.Conv2d(16, 32, kernel_size=5)
        self.rblock1 = ResidualBlock(16)
        self.rblock2 = ResidualBlock(32)
        self.mp = nn.MaxPool2d(2)
        self.l1 = torch.nn.Linear(512, 10)
        #self.l2 = torch.nn.Linear(256, 128)
        #self.l3 = torch.nn.Linear(128, 64)
        #self.l4 = torch.nn.Linear(64, 10)

    def forward(self, x):
        in_size = x.size(0)
        # 变成16*12*12
        x = F.relu(self.mp(self.conv1(x)))
        # 变成16*12*12
        x = self.rblock1(x)
        # 变成32*4*4
        x = F.relu(self.mp(self.conv2(x)))
        # 变成32*4*4
        x = self.rblock2(x)
        # 展开成全连接层
        x = x.view(in_size, -1)
        #x = F.relu(self.l1(x))
        #x = F.relu(self.l2(x))
        #x = F.relu(self.l3(x))
        x = self.l1(x)
        return x

model = Net4()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
criterion = torch.nn.CrossEntropyLoss()
#optimizer = torch.optim.SGD(model.parameters(),lr = 0.005,momentum=0.8,nesterov=True)
optimizer = torch.optim.Adam(model.parameters(),lr = 0.00025)

def time_since(since):
    s = time.time() - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)

def train(epoch,train_loader):
    running_loss = 0.0
    for batch_idx, data in enumerate(train_loader, 0):
        inputs, target = data
        inputs, target = inputs.to(device), target.to(device)
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()

        if batch_idx % 150 == 149:
            print(f'[{
      
      time_since(start)}] ', end='')
            print('[%d,%5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 150))
            running_loss = 0


def test(test_loader):
    correct = 0
    total = 0
    pred = []
    with torch.no_grad():  # 这部分代码不会计算梯度
        for data in test_loader:
            images, labels = data
            images,labels = images.to(device),labels.to(device)
            outputs = model(images)
            # 这里用max函数找输出节点中的最大值(即输出矩阵中每一行的最大值),返回该值和对应下标
            _, predicted = torch.max(outputs.data, dim=1)
            #转换成列表,并入总的预测列表中
            pred = pred + predicted.cpu().tolist()
            # labels.size(0)返回行数,也即是样本个数
            total += labels.size(0)
            # 把两个N*1的Tensor做比较相等是1否则是0,把所有结果相加就是正确的个数
            correct += (predicted == labels).sum().item()
    print("Total:",total)
    print("Corrcet:",correct)
    print('Accuracy on test set: %.2f %%' % (100 * correct / total))
    return pred,100 * correct / total

# 保存预测数据
def save_pred(preds, file):
    ''' Save predictions to specified file '''
    print('Saving results to {}'.format(file))
    with open(file, 'w', newline='') as fp:
        writer = csv.writer(fp)
        writer.writerow(['id', 'tested_num'])
        for i, p in enumerate(preds):
            writer.writerow([i, p])
#保存训练数据
def save_train_data(checkpoint_PATH):
    print("Saving training data......")
    torch.save({
    
    'epoch': save_epoch + epoch + 1, 'state_dict': model.state_dict(),
                'optimizer': optimizer.state_dict(), 'max_correct': max_correct},
               checkpoint_PATH)
#加载训练数据
def load_train_data(checkpoint_PATH,model,optimizer):
    print('loading train data......')
    if os.path.isfile(checkpoint_PATH):
        model_CKPT = torch.load(checkpoint_PATH)
        model.load_state_dict(model_CKPT['state_dict'])
        optimizer.load_state_dict(model_CKPT['optimizer'])
        maxCorrect = model_CKPT['max_correct']
        save_epoch = model_CKPT['epoch']
        print("Successfully Loading file,last max_correct is ",maxCorrect,"%",'total epoch is',save_epoch)
    return model, optimizer,maxCorrect,save_epoch

# 绘图函数
def plt(train_loss_list,test_loss_list):
    epoch = np.arange(1, len(train_loss_list) + 1, 1)
    train_loss_list = np.array(train_loss_list)
    plt.plot(epoch, train_loss_list)
    test_loss_list = np.array(test_loss_list)
    plt.plot(epoch, test_loss_list)
    plt.xlabel("Epoch")
    plt.ylabel('Accuracy')
    plt.grid()
    plt.show()

if __name__ == '__main__':
    max_correct = 0
    epochs = 50
    save_epoch = 0
    start = time.time()
    # 加载上次的训练数据
    model,optimizer,max_correct,save_epoch = load_train_data("model_AD.tar",model,optimizer)

    for epoch in range(epochs):
        train(epoch,train_loader)
        pred,correct = test(test_loader)
        if correct > max_correct:
            max_correct = correct
            save_train_data("model_AD.tar")

    print("The Highest correct rate: ", max_correct,"%")
    #载入模型
    model,optimizer,max_correct,save_epoch = load_train_data("model_AD.tar",model,optimizer)
    #制作预测文件
    pred, correct = test(test_loader)
    save_pred(pred, 'pred.csv')


第四个模型ResNet经过13个epoch的训练之后的识别准确率可以高达99.43%,数据处理,优化算法的选择,模型的选择,各种超参数的调节缺一不可。

猜你喜欢

转载自blog.csdn.net/tianjuewudi/article/details/117307141
今日推荐