Pytorch 卷积中的 Input Shape

2023-01-19 16:06:32

先看Pytorch中的卷积

class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

二维卷积层, 输入的尺度是(N, C_in,H,W),输出尺度(N,C_out,H_out,W_out)的计算方式
o u t ( N i , C o u t j ) = b i a s ( C o u t j ) + ∑ k = 0 C i n − 1 w e i g h t ( C o u t j , k ) ⨂ i n p u t ( N i , k ) out(N_i, C_{out_j})=bias(C_{out_j})+\sum^{C_{in}-1}_{k=0}weight(C_{out_j},k)\bigotimes input(N_i,k) out(Ni,Coutj)=bias(Coutj)+k=0Cin1weight(Coutj,k)input(Ni,k)

这里比较奇怪的是这个卷积层居然没有定义input shape,输入尺寸明明是:(N, C_in, H,W),但是定义中却只需要输入in_channel的size,就能完成卷积,那是不是说这样任意size的image都可以进行卷积呢?

然后我进行了下面这样的实验:

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 输入图像channel:1;输出channel:6;5x5卷积核
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 2x2 Max pooling
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # 除去批大小维度的其余维度
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

net = Net()
print(net)

输出

Net(
(conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)

官网Tutorial 说:这个网络(LeNet)的期待输入是32x32,我就比较奇怪他又没有设置Input shape或者Tensorflow里的Input层,怎么就知道(H,W) =(32, 32)。
输入:

input = torch.randn(1, 1, 32, 32)
output = Net(input)

没问题,但是

input = torch.randn(1, 1, 64, 64)
output = Net(input)

出现:mismatch Error

我们看一下卷积模型部分。
input:(1, 1, 32, 32) --> conv1(1, 6, 5) --> (1, 6, 28, 28) --> max_pool1(2, 2) --> (1, 6, 14, 14) --> conv2(6, 16, 5) -->(1, 16, 10, 10) --> max_pool2(2, 2) --> (1, 16, 5, 5)

然后是将其作为一个全连接网络的输入。Linear相当于tensorflow 中的Dense。所以当你的输入尺寸不为(32, 32)时,卷积得到最终feature map shape就不是(None, 16, 5, 5),而我们的第一个Linear层的输入为(None, 16 * 5 * 5),故会出现mismatch Error

之所以会有这样一个问题还是因为keras model 必须提定义Input shape,而pytorch更像是一个流程化操作,具体看官网吧。

  • 作者:weixin_43654661
  • 原文链接:https://blog.csdn.net/weixin_43654661/article/details/88757530
    更新时间:2023-01-19 16:06:32