简体   繁体   English

Output PyTorch 中卷积的尺寸

[英]Output Dimensions of convolution in PyTorch

The size of my input images are 68 x 224 x 3 (HxWxC), and the first Conv2d layer is defined as我的输入图像的大小是 68 x 224 x 3 (HxWxC),第一个Conv2d层定义为

conv1 = torch.nn.Conv2d(3, 16, stride=4, kernel_size=(9,9)) . conv1 = torch.nn.Conv2d(3, 16, stride=4, kernel_size=(9,9))

Why is the size of the output feature volume 16 x 15 x 54?为什么 output 特征体积的尺寸是 16 x 15 x 54? I get that there are 16 filters, so there is a 16 in the front, but if I use [(W−K+2P)/S]+1 to calculate dimensions, the dimensions are not divisible.我知道有 16 个过滤器,所以前面有 16 个,但是如果我使用[(W−K+2P)/S]+1来计算维度,则维度不可整除。

Can someone please explain?有人可以解释一下吗?

The calculation of feature maps is [(W−K+2P)/S]+1 and here [] brackets means floor division.特征图的计算是[(W−K+2P)/S]+1 ,这里[]括号表示楼层划分。 In your example padding is zero , so the calculation is [(68-9+2*0)/4]+1 ->[14.75]=14 -> [14.75]+1 = 15 and [(224-9+2*0)/4]+1 -> [53.75]=53 -> [53.75]+1 = 54 .在您的示例中,填充zero ,因此计算为[(68-9+2*0)/4]+1 ->[14.75]=14 -> [14.75]+1 = 15[(224-9+2*0)/4]+1 -> [53.75]=53 -> [53.75]+1 = 54

import torch

conv1 = torch.nn.Conv2d(3, 16, stride=4, kernel_size=(9,9))
input = torch.rand(1, 3, 68, 224)

print(conv1(input).shape)
# torch.Size([1, 16, 15, 54])

You may see different formulas too calculate feature maps.您也可能会看到不同的公式来计算特征图。

In PyTorch :PyTorch 中 在此处输入图像描述

In general, you may see this:一般来说,您可能会看到:

在此处输入图像描述

However the result of both cases are the same但是两种情况的结果是一样的

Was having same kind of inconvenience estimating output size of tensor after convolutional layer.在卷积层之后估计张量的 output 大小时遇到了同样的不便。 Check out a helper function I implemented at https://github.com/tuttelikz/conv_output_size .查看我在https://github.com/tuttelikz/conv_output_size实现的帮助程序 function。

Example:例子:

import torch
import torch.nn as nn
from conv_output_size import conv2d_output_size

c_i, c_o = 3, 16
k, s, p = 3, 2, 1

sample_2d_tensor = torch.ones((c_i, 64, 64))
c2d = nn.Conv2d(in_channels=c_i, out_channels=c_o, kernel_size=k,
                stride=s, padding=p)

output_size = conv2d_output_size(
    sample_2d_tensor.shape, out_channels=c_o, kernel_size=k, stride=s, padding=p)

print("After conv2d")
print("Dummy input size:", sample_2d_tensor.shape)
print("Calculated output size:", output_size)
print("Real output size:", c2d(sample_2d_tensor).detach().numpy().shape")

>>> After conv2d
>>> Dummy input size: torch.Size([3, 64, 64])
>>> Calculated output size: (16, 32, 32)
>>> Real output size: (16, 32, 32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM