第一次写博客,欢迎路过的各路大神指教~
本代码基于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)
网络参数分析: