pytorch张量与卷积计算

pytorch中张量的形状

在 PyTorch 中,张量的形状通常遵循 N x C x H x W 的顺序,其中:

  • N 表示批量大小(batch size),
  • C 表示通道数(number of channels),
  • H 表示高度(height),
  • W 表示宽度(width)。

因此,对于 PyTorch 中的图像数据,高度 H 通常在宽度 W 之前。这种顺序有时被称为“通道优先”(channel-first)格式,与某些其他深度学习框架(如 TensorFlow,它使用“通道最后”(channel-last)格式,即 N x H x W x C)不同。

卷积的计算公式

如果我们按照 PyTorch 的 $$N \times C \times H \times W$$ 格式来调整卷积层输出尺寸的计算公式,那么公式如下:

对于卷积层,给定输入特征图的尺寸为 $$N \times C_{in} \times H_{in} \times W_{in}$$,卷积核尺寸为 $$K_{h} \times K_{w}$$,填充为 $$P_{h} \times P_{w}$$,步长为 $$S_{h} \times S_{w}$$,输出特征图的尺寸 $$N \times C_{out} \times H_{out} \times W_{out}$$ 可以通过以下公式计算得出:

\[H_{out} = \left\lfloor \frac{H_{in} + 2 \times P_{h} - K_{h}}{S_{h}} + 1 \right\rfloor \]

\[W_{out} = \left\lfloor \frac{W_{in} + 2 \times P_{w} - K_{w}}{S_{w}} + 1 \right\rfloor \]

其中,$$\lfloor \cdot \rfloor$$ 表示向下取整。

对于池化层,如果池化核尺寸为 $$F_{h} \times F_{w}$$,步长为 $$S_{h} \times S_{w}$$,输出特征图的尺寸同样可以用类似的公式计算:

\[H_{pool} = \left\lfloor \frac{H_{in} - F_{h}}{S_{h}} + 1 \right\rfloor \]

\[W_{pool} = \left\lfloor \frac{W_{in} - F_{w}}{S_{w}} + 1 \right\rfloor \]

这些公式可以帮助我们预测卷积层或池化层之后的输出特征图尺寸,其中 $$H$$ 总是先于 $$W$$ 来表示高度和宽度。

posted @ 2024-08-31 15:16  JaxonYe  阅读(3)  评论(0编辑  收藏  举报