N
N
N:输出大小
W
W
W:输入大小
F
F
F:卷积核大小
P
P
P:填充值大小
S
S
S:步长大小
可知
N
=
(
W
+
2
P
−
F
)
/
S
+
1
N=(W+2P-F)/S+1
N=(W+2P−F)/S+1
以上针对填充paddding在上下或者左右都是相等的情况,待会讨论不相等的情况
推导:
按照卷积核对填充后的卷积区域进行扫描分析,可知
- 扫描区域大小: W + 2 P W+2P W+2P
- 图中第一行卷积核扫描的过程中,暂时不考虑第1次卷积核扫描,现在考虑第2次到第一行扫描结束的扫描区域大小,我称为“剩余扫描区域大小”,剩余扫描区域大小: W + 2 P − F W+2P-F W+2P−F
- 2步骤得到了剩余扫描区域大小,用卷积核以步长 S S S扫描剩余扫描区域,得到剩余扫描区域卷积后的大小: ( W + 2 P − F ) / S (W+2P-F)/S (W+2P−F)/S
- 最后考虑第一行的第1次卷积核扫描,与步骤3的剩余扫描区域卷积后的大小相加可得输出的大小: N = ( W + 2 P − F ) / S + 1 N=(W+2P-F)/S+1 N=(W+2P−F)/S+1
接下来考虑padding填充不相等的情况,思考方式不变,从分析实际扫描区域大小出发,假设输入图片大小是 W W W,填充大小 P P P在图像左边填充了 P 1 P1 P1,在图像右边填充了 P 2 P2 P2,那么扫描区域大小就变为: W + P 1 + P 2 W+P1+P2 W+P1+P2,最后的输出大小: N = ( W + P 1 + P 2 − F ) / S + 1 N=(W+P1+P2-F)/S+1 N=(W+P1+P2−F)/S+1
证毕
在实际的应用中,上述 N N N的输出不一定是整数,会因为padding的值导致出现小数的情况,pytorch和tensorflow都有自己的处理方式,详情见:pytorch中的卷积操作详解
在pytorch中,应用的是
N
=
(
W
+
P
1
+
P
2
−
F
)
/
S
+
1
N=(W+P1+P2-F)/S+1
N=(W+P1+P2−F)/S+1(向下取整)这个公式
然而在tensorflow中,应用会有点不同,padding有两种方式,一种是“VALID”,另一种是“SAME”
VALID:
N
=
(
W
−
F
+
1
)
/
S
N=(W-F+1)/S
N=(W−F+1)/S(向上取整),使用前需要自己手动设置padding值,处理输入图像,具体如下:
x = layers.ZeroPadding2D(((1, 2), (1, 2)))(input_image)# output(None, 227, 227, 3)
x = layers.Conv2D(48, kernel_size=11, strides=4, activation="relu")(x)# output(None, 55, 55, 48)
#参数说明
'''Arguments:
padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.
- If int: the same symmetric padding
is applied to height and width.
- If tuple of 2 ints:
interpreted as two different
symmetric padding values for height and width:
`(symmetric_height_pad, symmetric_width_pad)`.
- If tuple of 2 tuples of 2 ints:
interpreted as
`((top_pad, bottom_pad), (left_pad, right_pad))`'''
SAME: N = W / S N=W/S N=W/S(向上取整),padding自动设置,代码如下
x = layers.Conv2D(128, kernel_size=5, padding="same", activation="relu")(x)#output(None, 27, 27, 128)