【pytorch实现】卷积神经网络(2)

1.padding
直接用卷积核对对图像卷积,一个缺点是层数增加,输出的特征图会越来越小,不好再进行学习;还有就是图像边缘的像素点只被一个输出所使用,而内部的像素点可以被卷积多次,所以角落边缘区域的像素点在输出中采用的较少,就会丢掉图像边缘位置的信息。
把33填充成55,然后再卷积
在这里插入图片描述
一般来说,如果在高的两侧一共填充 ph 行,在宽的两侧一共填充 pw 列,所以输出特征图的尺寸:
(in_h-k_h+p_h+1)*(in_w-k_w+p_w+1)
在很多情况下,会设置 ph=kh−1 和 pw=kw−1 来使输入和输出具有相同的高和宽。
代码:

import torch
from torch import nn
# We define a convenience function to calculate the convolutional layer. This
# function initializes the convolutional layer weights and performs
# corresponding dimensionality elevations and reductions on the input and
# output
def comp_conv2d(conv2d, X):
    # (1,1) indicates that the batch size and the number of channels
    # (described in later chapters) are both 1
    X = X.reshape((1, 1) + X.shape)
    Y = conv2d(X)
    # Exclude the first two dimensions that do not interest us: batch and
    # channel
    return Y.reshape(Y.shape[2:])
# Note that here 1 row or column is padded on either side, so a total of 2
# rows or columns are added
conv2d = nn.Conv2d(1, 1, kernel_size=3, padding=1)
X = torch.rand(size=(8, 8))
comp_conv2d(conv2d, X).shape

结果:

torch.Size([8, 8])

当卷积核的高和宽不同时,我们也可以通过设置高和宽上不同的填充数使输出和输入具有相同的高和宽。

# Here, we use a convolution kernel with a height of 5 and a width of 3. The
# padding numbers on both sides of the height and width are 2 and 1,
# respectively
conv2d = nn.Conv2d(1, 1, kernel_size=(5, 3), padding=(2, 1))
comp_conv2d(conv2d, X).shape

结果:

torch.Size([8, 8])

2.stride
有时候为了计算效率或者降维,就可以将滑窗移动的步幅增大。我们将每次滑动的行数和列数称为步幅(stride)。
图5.3展示了在高上步幅为3、在宽上步幅为2的二维互相关运算。可以看到,输出第一列第二个元素时,卷积窗口向下滑动了3行,而在输出第一行第二个元素时卷积窗口向右滑动了2列。当卷积窗口在输入上再向右滑动2列时,由于输入元素无法填满窗口,无结果输出。
在这里插入图片描述
所以,当高上步幅为 sh ,宽上步幅为 sw 时,输出形状为:
⌊(nh−kh+ph+sh)/sh⌋×⌊(nw−kw+pw+sw)/sw⌋.
如果设置 ph=kh−1 和 pw=kw−1 ,那么输出形状将简化为:
⌊(nh+sh−1)/sh⌋×⌊(nw+sw−1)/sw⌋ 。更进一步,如果输入的高和宽能分别被高和宽上的步幅整除,那么输出形状将是**(nh/sh)×(nw/sw)**。
下面令高和宽上的步幅均为2,从而使输入的高和宽减半:
代码:

conv2d = nn.Conv2d(1, 1, kernel_size=3, padding=1, stride=2)
comp_conv2d(conv2d, X).shape
conv2d = nn.Conv2d(1, 1, kernel_size=(3, 5), padding=(0, 1), stride=(3, 4))
comp_conv2d(conv2d, X).shape

结果:

torch.Size([4, 4])
torch.Size([2, 2])

在默认情况下,填充为0,步幅为1。

手动@小宋是呢

猜你喜欢

转载自blog.csdn.net/laozaoxiaowanzi/article/details/107384137