微调ResNet18 on MNIST精度99.59%以上

时间20210408
新人,各位观众老爷给个鼓励,谢谢!
作者:知道许多的橘子
实现:Resnet18对MNIST数据集的分类,作为一个入门
测试集准确度:99.59%
实现框架pytorch
数据增强方法:Normalize
训练次数:60
阶段学习率[0-20]:0.001||[20-40]:0.0003||[40-60]:0.0001
优化器:optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
如果感觉算力不够用了,或者心疼自己电脑了!
可以用我实验室的算力,试试呢!
害,谁叫我的算力都用不完呢!
支持所有框架!实际上框架都配置好了!
傻瓜式云计算!
Tesla v100 1卡,2卡,4卡,8卡
内存16-128G
cpu:8-24核
想要?加个微信:15615634293
或者点这里,找我!
欢迎打扰!
# In[1] 导入所需工具包
import torch
import torch.nn as nn
import torchvision
from torchvision import datasets,transforms
import time
from torch.nn import functional as F
from math import floor, ceil
#import torchvision.transforms as transforms
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
# In[1] 设置超参数
num_epochs = 60
batch_size = 100
learning_rate = 0.001

# In[2] 获取数据包括训练数据和测试数据
train_loader =torch.utils.data.DataLoader(
        torchvision.datasets.MNIST('MNIST',train=True,download=True,
                                   transform=torchvision.transforms.Compose([
                                           torchvision.transforms.ToTensor(),
                                           torchvision.transforms.Normalize(
                                                   (0.1307,),(0.3081,))
                                           ])),
        batch_size=batch_size,shuffle=True)

test_loader =torch.utils.data.DataLoader(
        torchvision.datasets.MNIST('MNIST',train=False,download=True,
                                   transform=torchvision.transforms.Compose([
                                           torchvision.transforms.ToTensor(),
                                           torchvision.transforms.Normalize(
                                                   (0.1307,),(0.3081,))
                                           ])),
        batch_size=batch_size,shuffle=True)
# In[1] 定义卷积核
def conv3x3(in_channels, out_channels, stride=1):
    return nn.Conv2d(in_channels, out_channels, kernel_size=3,
                     stride=stride, padding=1, bias=True)

# In[1] 定义残差块
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(ResidualBlock, self).__init__()
        self.conv1 = conv3x3(in_channels, out_channels, stride)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(out_channels, out_channels)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.downsample = downsample

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        # 下采样
        if self.downsample:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out
# In[1] 搭建残差神经网络
class ResNet(nn.Module):
    def __init__(self, block, layers, num_classes=10):
        super(ResNet, self).__init__()
        self.in_channels = 16
        self.conv = conv3x3(1, 16)
        self.bn = nn.BatchNorm2d(16)
        self.relu = nn.ReLU(inplace=True)
        # 构建残差块,恒等映射
        # in_channels == out_channels and stride = 1 所以这里我们构建残差块,没有下采样
        self.layer1 = self.make_layer(block, 16, layers[0], stride=1)
        # 不构建残差块,进行了下采样
        # layers中记录的是数字,表示对应位置的残差块数目
        self.layer2 = self.make_layer(block, 32, layers[1], 2)
        # 不构建残差块,进行了下采样
        self.layer3 = self.make_layer(block, 64, layers[2], 2)
        self.avg_pool = nn.AvgPool2d(8)
        self.fc1 = nn.Linear(3136, 128)
        self.normfc12 = nn.LayerNorm((128), eps=1e-5)
        self.fc2 = nn.Linear(128, num_classes)

    def make_layer(self, block, out_channels, blocks, stride=1):
        downsample = None
        if (stride != 1) or (self.in_channels != out_channels):
            downsample = nn.Sequential(
                conv3x3(self.in_channels, out_channels, stride=stride),
                nn.BatchNorm2d(out_channels))
        layers = []
        layers.append(block(self.in_channels, out_channels, stride, downsample))
        # 当out_channels = 32时,in_channels也变成32了
        self.in_channels = out_channels
        # blocks是残差块的数目
        # 残差块之后的网络结构,是out_channels->out_channels的
        # 可以说,make_layer做的是输出尺寸相同的所有网络结构
        # 由于输出尺寸会改变,我们用make_layers去生成一大块对应尺寸完整网络结构
        for i in range(1, blocks):
            layers.append(block(out_channels, out_channels))
        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.conv(x)
        out = self.bn(out)
        out = self.relu(out)
        # layer1是三块in_channels等于16的网络结构,包括三个恒等映射
        out = self.layer1(out)
        # layer2包括了16->32下采样,然后是32的三个恒等映射
        out = self.layer2(out)
        # layer3包括了32->64的下采样,然后是64的三个恒等映射
        out = self.layer3(out)
        #out = self.avg_pool(out)
        # 全连接压缩
        # out.size(0)可以看作是batch_size
        out = out.view(out.size(0), -1)
        out = self.fc1(out)
        out = self.normfc12(out)
        out = self.relu(out)
        out = self.fc2(out)
        return out
# In[1] 定义模型和损失函数
# [2,2,2]表示的是不同in_channels下的恒等映射数目
model = ResNet(ResidualBlock, [2, 2, 2]).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# In[1] 设置一个通过优化器更新学习率的函数
def update_lr(optimizer, lr):
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
# In[1] 定义测试函数
def test(model,test_loader):
    
    model.eval()
    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('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

        
# In[1] 训练模型更新学习率
total_step = len(train_loader)
curr_lr = learning_rate
for epoch in range(num_epochs):
    in_epoch = time.time()
    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(model,test_loader)
    out_epoch = time.time()
    print(f"use {(out_epoch-in_epoch)//60}min{(out_epoch-in_epoch)%60}s")
    if (epoch + 1) % 20 == 0:
        curr_lr /= 3
        update_lr(optimizer, curr_lr)
# In[1] 测试模型并保存
model.eval()
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('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

torch.save(model.state_dict(), 'resnet.ckpt')
cuda
Epoch [1/60], Step [100/600] Loss: 0.0817
Epoch [1/60], Step [200/600] Loss: 0.0185
Epoch [1/60], Step [300/600] Loss: 0.0325
Epoch [1/60], Step [400/600] Loss: 0.1492
Epoch [1/60], Step [500/600] Loss: 0.1131
Epoch [1/60], Step [600/600] Loss: 0.0087
Accuracy of the model on the test images: 99.03 %
use 0.0min18.335710287094116s
Epoch [2/60], Step [100/600] Loss: 0.0504
Epoch [2/60], Step [200/600] Loss: 0.1095
Epoch [2/60], Step [300/600] Loss: 0.1329
Epoch [2/60], Step [400/600] Loss: 0.0889
Epoch [2/60], Step [500/600] Loss: 0.0196
Epoch [2/60], Step [600/600] Loss: 0.0263
Accuracy of the model on the test images: 99.05 %
use 0.0min17.68439769744873s
Epoch [3/60], Step [100/600] Loss: 0.0244
Epoch [3/60], Step [200/600] Loss: 0.0551
Epoch [3/60], Step [300/600] Loss: 0.0242
Epoch [3/60], Step [400/600] Loss: 0.0272
Epoch [3/60], Step [500/600] Loss: 0.0049
Epoch [3/60], Step [600/600] Loss: 0.0472
Accuracy of the model on the test images: 99.08 %
use 0.0min17.7007839679718s
Epoch [4/60], Step [100/600] Loss: 0.0346
Epoch [4/60], Step [200/600] Loss: 0.0120
Epoch [4/60], Step [300/600] Loss: 0.0021
Epoch [4/60], Step [400/600] Loss: 0.0050
Epoch [4/60], Step [500/600] Loss: 0.0097
Epoch [4/60], Step [600/600] Loss: 0.0522
Accuracy of the model on the test images: 99.3 %
use 0.0min17.670555114746094s
Epoch [5/60], Step [100/600] Loss: 0.0028
Epoch [5/60], Step [200/600] Loss: 0.0111
Epoch [5/60], Step [300/600] Loss: 0.0108
Epoch [5/60], Step [400/600] Loss: 0.0018
Epoch [5/60], Step [500/600] Loss: 0.0610
Epoch [5/60], Step [600/600] Loss: 0.0345
Accuracy of the model on the test images: 99.26 %
use 0.0min17.79431986808777s
Epoch [6/60], Step [100/600] Loss: 0.0010
Epoch [6/60], Step [200/600] Loss: 0.0095
Epoch [6/60], Step [300/600] Loss: 0.0013
Epoch [6/60], Step [400/600] Loss: 0.0085
Epoch [6/60], Step [500/600] Loss: 0.0027
Epoch [6/60], Step [600/600] Loss: 0.0252
Accuracy of the model on the test images: 99.06 %
use 0.0min17.835293769836426s
Epoch [7/60], Step [100/600] Loss: 0.0406
Epoch [7/60], Step [200/600] Loss: 0.0022
Epoch [7/60], Step [300/600] Loss: 0.0005
Epoch [7/60], Step [400/600] Loss: 0.0031
Epoch [7/60], Step [500/600] Loss: 0.0008
Epoch [7/60], Step [600/600] Loss: 0.0170
Accuracy of the model on the test images: 99.24 %
use 0.0min17.662654638290405s
Epoch [8/60], Step [100/600] Loss: 0.0009
Epoch [8/60], Step [200/600] Loss: 0.0026
Epoch [8/60], Step [300/600] Loss: 0.0040
Epoch [8/60], Step [400/600] Loss: 0.0008
Epoch [8/60], Step [500/600] Loss: 0.0005
Epoch [8/60], Step [600/600] Loss: 0.0024
Accuracy of the model on the test images: 98.71 %
use 0.0min17.942986488342285s
Epoch [9/60], Step [100/600] Loss: 0.0005
Epoch [9/60], Step [200/600] Loss: 0.0008
Epoch [9/60], Step [300/600] Loss: 0.0010
Epoch [9/60], Step [400/600] Loss: 0.0200
Epoch [9/60], Step [500/600] Loss: 0.0171
Epoch [9/60], Step [600/600] Loss: 0.0024
Accuracy of the model on the test images: 99.23 %
use 0.0min17.72422456741333s
Epoch [10/60], Step [100/600] Loss: 0.0007
Epoch [10/60], Step [200/600] Loss: 0.0084
Epoch [10/60], Step [300/600] Loss: 0.0002
Epoch [10/60], Step [400/600] Loss: 0.0007
Epoch [10/60], Step [500/600] Loss: 0.0007
Epoch [10/60], Step [600/600] Loss: 0.0229
Accuracy of the model on the test images: 99.15 %
use 0.0min17.694152116775513s
Epoch [11/60], Step [100/600] Loss: 0.0103
Epoch [11/60], Step [200/600] Loss: 0.0186
Epoch [11/60], Step [300/600] Loss: 0.0355
Epoch [11/60], Step [400/600] Loss: 0.0014
Epoch [11/60], Step [500/600] Loss: 0.0118
Epoch [11/60], Step [600/600] Loss: 0.0038
Accuracy of the model on the test images: 99.4 %
use 0.0min17.857590675354004s
Epoch [12/60], Step [100/600] Loss: 0.0001
Epoch [12/60], Step [200/600] Loss: 0.0001
Epoch [12/60], Step [300/600] Loss: 0.0008
Epoch [12/60], Step [400/600] Loss: 0.0001
Epoch [12/60], Step [500/600] Loss: 0.0007
Epoch [12/60], Step [600/600] Loss: 0.0005
Accuracy of the model on the test images: 99.25 %
use 0.0min17.56403350830078s
Epoch [13/60], Step [100/600] Loss: 0.0018
Epoch [13/60], Step [200/600] Loss: 0.0809
Epoch [13/60], Step [300/600] Loss: 0.0101
Epoch [13/60], Step [400/600] Loss: 0.0036
Epoch [13/60], Step [500/600] Loss: 0.0009
Epoch [13/60], Step [600/600] Loss: 0.0182
Accuracy of the model on the test images: 99.19 %
use 0.0min17.759077072143555s
Epoch [14/60], Step [100/600] Loss: 0.0014
Epoch [14/60], Step [200/600] Loss: 0.0371
Epoch [14/60], Step [300/600] Loss: 0.0003
Epoch [14/60], Step [400/600] Loss: 0.0143
Epoch [14/60], Step [500/600] Loss: 0.0002
Epoch [14/60], Step [600/600] Loss: 0.0371
Accuracy of the model on the test images: 99.17 %
use 0.0min17.763488292694092s
Epoch [15/60], Step [100/600] Loss: 0.0002
Epoch [15/60], Step [200/600] Loss: 0.0002
Epoch [15/60], Step [300/600] Loss: 0.0000
Epoch [15/60], Step [400/600] Loss: 0.0001
Epoch [15/60], Step [500/600] Loss: 0.0000
Epoch [15/60], Step [600/600] Loss: 0.0018
Accuracy of the model on the test images: 99.26 %
use 0.0min17.66961097717285s
Epoch [16/60], Step [100/600] Loss: 0.0002
Epoch [16/60], Step [200/600] Loss: 0.0001
Epoch [16/60], Step [300/600] Loss: 0.0394
Epoch [16/60], Step [400/600] Loss: 0.0123
Epoch [16/60], Step [500/600] Loss: 0.0000
Epoch [16/60], Step [600/600] Loss: 0.0323
Accuracy of the model on the test images: 99.33 %
use 0.0min17.823559761047363s
Epoch [17/60], Step [100/600] Loss: 0.0019
Epoch [17/60], Step [200/600] Loss: 0.0004
Epoch [17/60], Step [300/600] Loss: 0.0005
Epoch [17/60], Step [400/600] Loss: 0.0003
Epoch [17/60], Step [500/600] Loss: 0.0004
Epoch [17/60], Step [600/600] Loss: 0.0014
Accuracy of the model on the test images: 99.4 %
use 0.0min17.818267107009888s
Epoch [18/60], Step [100/600] Loss: 0.0026
Epoch [18/60], Step [200/600] Loss: 0.0069
Epoch [18/60], Step [300/600] Loss: 0.0042
Epoch [18/60], Step [400/600] Loss: 0.0014
Epoch [18/60], Step [500/600] Loss: 0.0010
Epoch [18/60], Step [600/600] Loss: 0.0003
Accuracy of the model on the test images: 99.39 %
use 0.0min17.786447763442993s
Epoch [19/60], Step [100/600] Loss: 0.0001
Epoch [19/60], Step [200/600] Loss: 0.0002
Epoch [19/60], Step [300/600] Loss: 0.0001
Epoch [19/60], Step [400/600] Loss: 0.0001
Epoch [19/60], Step [500/600] Loss: 0.0384
Epoch [19/60], Step [600/600] Loss: 0.0019
Accuracy of the model on the test images: 99.32 %
use 0.0min17.744271516799927s
Epoch [20/60], Step [100/600] Loss: 0.0050
Epoch [20/60], Step [200/600] Loss: 0.0001
Epoch [20/60], Step [300/600] Loss: 0.0023
Epoch [20/60], Step [400/600] Loss: 0.0000
Epoch [20/60], Step [500/600] Loss: 0.0034
Epoch [20/60], Step [600/600] Loss: 0.0008
Accuracy of the model on the test images: 99.35 %
use 0.0min17.80747652053833s
Epoch [21/60], Step [100/600] Loss: 0.0001
Epoch [21/60], Step [200/600] Loss: 0.0001
Epoch [21/60], Step [300/600] Loss: 0.0003
Epoch [21/60], Step [400/600] Loss: 0.0000
Epoch [21/60], Step [500/600] Loss: 0.0003
Epoch [21/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.46 %
use 0.0min17.777599573135376s
Epoch [22/60], Step [100/600] Loss: 0.0003
Epoch [22/60], Step [200/600] Loss: 0.0001
Epoch [22/60], Step [300/600] Loss: 0.0000
Epoch [22/60], Step [400/600] Loss: 0.0000
Epoch [22/60], Step [500/600] Loss: 0.0003
Epoch [22/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.55 %
use 0.0min17.79033088684082s
Epoch [23/60], Step [100/600] Loss: 0.0000
Epoch [23/60], Step [200/600] Loss: 0.0002
Epoch [23/60], Step [300/600] Loss: 0.0000
Epoch [23/60], Step [400/600] Loss: 0.0000
Epoch [23/60], Step [500/600] Loss: 0.0000
Epoch [23/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.59 %
use 0.0min17.915147304534912s
Epoch [24/60], Step [100/600] Loss: 0.0001
Epoch [24/60], Step [200/600] Loss: 0.0000
Epoch [24/60], Step [300/600] Loss: 0.0000
Epoch [24/60], Step [400/600] Loss: 0.0000
Epoch [24/60], Step [500/600] Loss: 0.0000
Epoch [24/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.57 %
use 0.0min17.72119116783142s
Epoch [25/60], Step [100/600] Loss: 0.0001
Epoch [25/60], Step [200/600] Loss: 0.0001
Epoch [25/60], Step [300/600] Loss: 0.0001
Epoch [25/60], Step [400/600] Loss: 0.0000
Epoch [25/60], Step [500/600] Loss: 0.0000
Epoch [25/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.57 %
use 0.0min17.888681411743164s
Epoch [26/60], Step [100/600] Loss: 0.0000
Epoch [26/60], Step [200/600] Loss: 0.0000
Epoch [26/60], Step [300/600] Loss: 0.0000
Epoch [26/60], Step [400/600] Loss: 0.0000
Epoch [26/60], Step [500/600] Loss: 0.0000
Epoch [26/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.56 %
use 0.0min17.78260850906372s
Epoch [27/60], Step [100/600] Loss: 0.0000
Epoch [27/60], Step [200/600] Loss: 0.0000
Epoch [27/60], Step [300/600] Loss: 0.0000
Epoch [27/60], Step [400/600] Loss: 0.0000
Epoch [27/60], Step [500/600] Loss: 0.0000
Epoch [27/60], Step [600/600] Loss: 0.0001
Accuracy of the model on the test images: 99.57 %
use 0.0min17.75735902786255s
Epoch [28/60], Step [100/600] Loss: 0.0000
Epoch [28/60], Step [200/600] Loss: 0.0000
Epoch [28/60], Step [300/600] Loss: 0.0000
Epoch [28/60], Step [400/600] Loss: 0.0000
Epoch [28/60], Step [500/600] Loss: 0.0000
Epoch [28/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.57 %
use 0.0min17.589683771133423s
Epoch [29/60], Step [100/600] Loss: 0.0000
Epoch [29/60], Step [200/600] Loss: 0.0000
Epoch [29/60], Step [300/600] Loss: 0.0000
Epoch [29/60], Step [400/600] Loss: 0.0000
Epoch [29/60], Step [500/600] Loss: 0.0000
Epoch [29/60], Step [600/600] Loss: 0.0000
Accuracy of the model on the test images: 99.57 %
use 0.0min17.815569400787354s
Epoch [30/60], Step [100/600] Loss: 0.0000
Epoch [30/60], Step [200/600] Loss: 0.0000
Epoch [30/60], Step [300/600] Loss: 0.0000

你可能感兴趣的:(笔记,pytorch,深度学习,神经网络,机器学习)