在Tensorflow中构建Resnet模型时,为什么要使用固定填充

Kes*_*ieh 7 python tensorflow resnet

Tensorflow在github中具有resnet的正式实现。并且它使用固定填充而不是普通的tf.layers.conv2d。

像这样:

def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):
  """Strided 2-D convolution with explicit padding."""
  # The padding is consistent and is based only on `kernel_size`, not on the
  # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
  if strides > 1:
    inputs = fixed_padding(inputs, kernel_size, data_format)

  return tf.layers.conv2d(
      inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides,
      padding=('SAME' if strides == 1 else 'VALID'), use_bias=False,
      kernel_initializer=tf.variance_scaling_initializer(),
      data_format=data_format)
Run Code Online (Sandbox Code Playgroud)

这样做的目的是什么?如果输入大小为32x32的图像并使用tf.layer.conv2d将填充方法设置为SAME,则跨度为2,则可以得到16x16的特征图。但是在上面的代码中,它将在图像的两边填充零,然后使用填充方法有效。

小智 6

假设我们的步幅为 2,内核大小为 3。

tf.layers.conv2d与填充一起使用SAME

情况1:

                   pad|              |pad
       inputs:      0 |1  2  3  4  5 |0 
                   |_______|
                         |_______|
                               |_______|
Run Code Online (Sandbox Code Playgroud)

案例2:

                                     |pad
       inputs:      1  2  3  4  5  6 |0 
                   |_______|
                         |_______|
                               |_______|
Run Code Online (Sandbox Code Playgroud)

您可以看到填充将取决于输入大小。确定相同的填充使得输出大小为Math.ceil(input_size / stride)。您可以在此处阅读更多相关信息。

使用 resnet 的固定填充实现:

情况1:

                   pad|              |pad
       inputs:      0 |1  2  3  4  5 |0 
                   |_______|
                         |_______|
                               |_______|
Run Code Online (Sandbox Code Playgroud)

案例2:

                   pad|                 |pad
       inputs:      0 |1  2  3  4  5  6 |0 
                   |_______|
                         |_______|
                               |_______|
Run Code Online (Sandbox Code Playgroud)

填充由内核大小唯一定义,并且与输入大小无关。


Mil*_*ore 1

如您所知,RNN 具有这些跳过连接,其中网络如下所示: 在此输入图像描述

方程变为:

F(x) + x   // Here 'x' is not input but the the kernel/filter. 
Run Code Online (Sandbox Code Playgroud)

F(x)因此,通过这个加法,我们假设 和的维度x将相同。但如果不是这样,我们必须填充它们以使卷积发生。

这就是您在ResNet TF 模型padding="SAME"中看到所有卷积都有填充的原因