手写字体识别MINST的两种方法

作为Pytorch初学者,利用MNIST数据集作为基本数据集,使用Pytorch进行搭建模型训练。

MNIST数据集小,训练较容易。

训练数据集的长度为:60000
测试数据集的长度为:10000

1、方法一,线性连接层

一共五层网络,第一层输入7844,第二层520,第三层320,第四层240,第五层120,最后输出分类字符0——9共十种类,因此,最后一层为10.该方法 简单。线性连接,准确率低。

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.l1 = nn.Linear(784, 520)
        self.l2 = nn.Linear(520, 320)
        self.l3 = nn.Linear(320, 240)
        self.l4 = nn.Linear(240, 120)
        self.l5 = nn.Linear(120, 10)

    def forward(self, x):
        x = x.view(-1, 784)  # flatten the data (n, 1, 28,28 )_-》(n,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))
        x = F.relu(self.l5(x))
        return x

 该方法简单,容易实现。准确率不高,误差大。不建议用。不过用于方便理解。

Test  set: Average loss :0.0123,Accuracy:6824/10000(68%)

2、方法二,卷积神经CNN

 

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(
                in_channels=1,  # size of input channels
                out_channels=16,  # size of input channels
                kernel_size=(5, 5),  # size of filter
                stride=(1, 1),  # step of filter
                padding=2,  # padding num
            ),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(16, 32, (5, 5), (1, 1), 2),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        self.flat = nn.Flatten()  # flattern the result
        self.out = nn.Linear(32 * 7 * 7, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.flat(x)
        out = self.out(x)
        return out

该方法快速,准确度高。建议初学者多加练习。

Test  set: Average loss :0.0006,Accuracy:9859/10000(99%)

推荐使用这个进行初学练习。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值