【TensorFlow】conv2d函数参数解释以及padding理解

conv2d函数

CNN在深度学习中有着举足轻重的地位,主要用于特征提取。在TensorFlow中涉及的函数是tf.nn.conv2d。

tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format=”NHWC”, dilations=[1, 1, 1, 1], name=None)

  • input 代表做卷积的输入图像的Tensor,其shape要求为[batch, in_height, in_width, in_channels],具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],数据类型为float32或float64;
  • filter 相当于CNN中的卷积核,该Tensor的shape要求为[filter_height, filter_width, in_channels, out_channels],具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,filter的通道数要求与input的in_channels一致,即第三维in_channels,就是参数input的第四维;
  • strides [1,stride_h,stride_w,1]步长,即卷积核每次移动的步长;
  • padding 填充模式,取值只能为“SAME”或“VALID”;

输出结果是shape为[batch, out_height, out_width, out_channels],batch取决于input,out_channels取决于filter,而out_height与out_width取决于所有参数。

  • SAME模式
    • out_height = ceil ( float ( in_height ) / float ( stride_h) )
    • out_width = ceil ( float ( in_width ) / float ( stride_w ) )
  • VALID模式
    • out_height = ceil(float(in_height - filter_height + 1) / float(stride_h))
    • out_width = ceil(float(in_width - filter_width + 1) / float(stride_w))

补的方式如下:

  • 补的行数:pad_along_height = max((out_height - 1) * strides[1] + filter_height - in_height, 0)
  • 补的列数:pad_along_width = max((out_width - 1) * strides[2] + filter_width - in_width, 0)

  • pad_top = pad_along_height // 2

  • pad_bottom = pad_along_height - pad_top
  • pad_left = pad_along_width // 2
  • pad_right = pad_along_width - pad_left

测试实例

import tensorflow as tf

input = tf.Variable(tf.random_normal([1,16,64,3]))
filter = tf.Variable(tf.random_normal([3,5,3,32]))
op = tf.nn.conv2d(input, filter, strides=[1, 2, 2, 1], padding='VALID')

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    res = (sess.run(op))
    print (res.shape)

# (1, 7, 30, 32)

后续学习资料

参考

猜你喜欢

转载自blog.csdn.net/callinglove/article/details/80791212