Pytorch菜鸟入门(4)——快速搭建CNN训练MINIST和Fashion-MNIST【代码】
- 本系列文章为小白针对Morvan的课程中Pytorch学习过程中理解和记录,用于自己复习回顾,可参考。
CNN搭建与训练MINIST数据集
MNIST数据导入
构建CNN
这个CNN构造了两层卷积层,1层全连接层。
以第一层conv1为例:
可用self.conv1=nn.Conv2d(in_channels,out_channels,kernal_Size,stride,padding),
in_channels一般为前一层的过滤器个数,但是第一层的时候,为输入图像的通道数,由于数据是黑白的,可认为in_channels为1。
out_channels为过滤器个数
kernal_size为过滤器的大小,一般filter和kernal是一个意思。
stride是步长
padding是填充
强推吴恩达系列视频,很清楚!
一般input为Nw,Nh,Nc(#channels)
有N个filters,且filters为大小为f,f,Nc(#channels)
则output为Nw2,Nh2,N
Nw2=(Nw+2p-f/s)[取<=该值的整数]+1
Nh2=(Nh+2p-f/s)[取<=该值的整数]+1
N为过滤器个数
下面代码中需要注意的是
但是一般若保证输入输出图片大小不缩小,一般则stride=1,padding=f-1/2。本代码的两个卷积层都是这样。
但注意,有了池化MAXPOOL2d,这个相当于多了过滤器,将output size里的height和weight都缩小了kernal_size倍。
也是为什么conv1的输出是(16,28,28)
但是conv2的输入就是(16,14,14)了
因为二者之间存在maxpool2d(kernal_size=2).
训练MINIST数据
同时输出前十个数据看是否准确
for epoch in range(EPOCH):
for step, (b_x, b_y) in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader
output = cnn(b_x)[0] # cnn output
loss = loss_func(output, b_y) # cross entropy loss
optimizer.zero_grad() # clear gradients for this training step
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
if step % 50 == 0:
test_output, last_layer = cnn(test_x)
pred_y = torch.max(test_output, 1)[1].data.numpy()
accuracy = float((pred_y == test_y.data.numpy()).astype(int).sum()) / float(test_y.size(0))
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data.numpy(), '| test accuracy: %.2f' % accuracy)
# print 10 predictions from test data
test_output, _ = cnn(test_x[:10])
pred_y = torch.max(test_output, 1)[1].data.numpy()
print(pred_y, 'prediction number')
print(test_y[:10].numpy(), 'real number')
训练Fashion-MNIST数据集
=未完待续==2020/02/02