Pytorch菜鸟入门(4)——快速搭建CNN训练MINIST和Fashion-MNIST

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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值