pytorch里简单神经网络的参数理解

第一次写博客,欢迎路过的各路大神指教~

 

本代码基于pytorch0.4

这里记录一下我对pytorch里卷积、最大池化、全连接的理解,分析了网络参数:

1.输入图片大小:1×1×5×5

2.建立一层conv1:1×6×(2×2)stride=1,即6通道、大小2×2、步长为1的卷积核

3.建立max_pool2d:2×2,stride=1,这里注意需设置stride=1,因为max_pool2d()默认stride=None(不懂是什么意思,请指教)。而且这里的max_pool2d可能比你想象的要复杂,多了一个重要的参数:dilation 。
具体请移步:https://pytorch.org/docs/stable/nn.html?highlight=max_pool#torch.nn.MaxPool2d

4.将卷积的结果“铺平:x.view(),即将feature map 展开成一维tensor,便于连接 全连接层

5.建立全连接层:输入:1×54,输出:1×4

代码如下:

import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 2)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(6 * 3 * 3, 4)
    def forward(self, x):
        # Max pooling over a (2, 2) window
        print(x.size())
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2),stride=1)
        print('================')
        print(x.size())
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        return x
    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features
if __name__ =='__main__':
    net = Net()
    print(net)
    params = list(net.parameters())
    print(len(params))
    print(params[0].size())
    print(params[1].size())
    print(params[2].size())
    print(params[3].size())  # conv1's .weight
    input = Variable(torch.randn(1, 1, 5, 5))
    output = net(input)

网络参数分析:

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值