作为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%)
推荐使用这个进行初学练习。