三层CNN实现手写数字识别(新手项目)

最近刚刚用三层全连接层实现了一下手写数字识别(可以看我的另一个博客),后来发现全连接对图像的像素是独立分析的,所以训练慢,在6万的训练集下,要训练10次左右才会有较好的效果。查阅一些资料以后发现用CNN进行训练会考虑图像像素之间的关联性,训练效果会好一点,所以用CNN来练一下手。
果然,用CNN只训练了1次就达到了很好的效果,超过三次的训练次数都会导致训练效果急剧下降。

训练效果图

在这里插入图片描述

模型代码:

from torch import nn
from torch.nn.modules.activation import ReLU
from torch.nn.modules.pooling import MaxPool2d

class CNN(nn.Module):
    def __init__(self):
        super(CNN,self).__init__()
        self.conv1=nn.Sequential(#input(1,1,28,28)
            nn.Conv2d(in_channels=1,
                    out_channels=16,
                    kernel_size=3,
                    stride=1,
                    padding=1),#output:(1,16,28,28)
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2)#output:(1,16,14,14)
        )
        self.conv2=nn.Sequential(
            nn.Conv2d(
                in_channels=16,
                out_channels=32,
                kernel_size=3,
                stride=1,
                padding=1
            ),#output(32,14,14)
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2)#output(1,32,7,7)
        )
        self.conv3=nn.Linear(32*7*7,10)

    def forward(self,x):
        x=self.conv1(x)
        x=self.conv2(x)
        x=x.view(x.size(0),-1)#input:(1,32,7,7)   output:(1,32*7*7)
        x=self.conv3(x)
        return x


if __name__= "main":
	#cnn=CNN()
	# print(cnn)
    

训练模型代码:

from matplotlib import pyplot as plt
import torch
import numpy as np
import time
from torchvision import datasets ,transforms
from torch import nn
from torch import optim
from CNNmodel import CNN

#定义转换器,包含操作:将图像转为tensor和(0,1)之间,将数据转换为(-1,1)
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5,),(0.5,))
                            ])
#下载数据集
dataset = datasets.MNIST('MNIST_data',download=False,transform=transform)

#加载数据集,定义训练批次为1
trainloader = torch.utils.data.DataLoader(dataset=dataset,batch_size=1)

model=CNN()

criterion=nn.CrossEntropyLoss()
#随机梯度下降
optimizer=optim.Adam(model.parameters(),lr=0.005)

#设置迭代次数为1次,由于数据集过多,3次训练以上会导致模型过拟合
epoch=1
k=0
start_time=time.time()
for e in range(epoch):
    running_loss=0
    #训练一个批次,image是图像,labels是标签
    for images ,labels in trainloader:
        k+=1
        output=model(images)
        optimizer.zero_grad()
        loss=criterion(output,labels)
        loss.backward()
        optimizer.step()
        running_loss+=loss.item()
        if(k%1000==0):
            print(k/1000)
    else:
        print(f"第{e}代,训练损失:{running_loss/len(trainloader)}")
print("共花费时间:",time.time()-start_time)
#验证集,利用matplotlib画图
images,labels=next(iter(trainloader))

with torch.no_grad():
    logits=model.forward(images)
result=torch.softmax(logits,dim=1)
result=result.data.numpy().squeeze()
fig,(ax1,ax2) = plt.subplots(figsize=(6,9),ncols=2)
ax1.imshow(images.resize_(1,28,28).numpy().squeeze())
ax1.axis("off")
ax2.barh(np.arange(10),result)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(10))
ax2.set_yticklabels(np.arange(10))
ax2.set_xlim(0,1.1)

plt.tight_layout()
plt.show()

#保存模型
torch.save(model,"weight.pth")

因为只是练练手,对准确率没有很高的要求,所以学习率设置的比较高,但是训练效果来看,正确率还是可以接受。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值