您的位置:首页 > 其它

TensorFlow中padding的 'SAME' 和 'VALID' 参数

2018-03-27 22:47 495 查看

VALID

conv2d中
VALID
参数不会在输入上添加新的像素,输出图片的宽度的计算公式为

output_width = [(input_width - kernel_size + 1) / stride]


其中
[ ]
表示结果向上取整,输出图像的宽度计算类似

SAME

conv2d中
SAME
参数会填充0,确保卷积结果覆盖输入图像的所有像素点,计算宽度的公式为

output_width = [input_width / stride]


这时需要填充的列数是:

output_padding_width = (output_width - 1) x stride + kernel_size - input_width


右边需要填充的列数为

output_padding_right = [output_padding_width / 2]


左边需要填充的列数为

output_padding_left = output_padding_width - output_padding_right


也就是说,右边是优先填充的,如果只需要填充1行的话,会填充在右边

贴一个具体的tensorflow的例子

import tensorflow as tf
import numpy as np

def weight_variable(shape):
return tf.Variable(tf.ones(shape))

image = np.array([[1,2,3],[4,5,6],[7,8,9]], dtype=np.float32)
image = np.reshape(image,(1,3,3,1))

W = weight_variable([2, 2, 1, 1])

conv_valid = tf.nn.conv2d(image, W, strides=[1, 2, 2, 1], padding="VALID")
conv_same  = tf.nn.conv2d(image, W, strides=[1, 2, 2, 1], padding="SAME")

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

print(conv_valid.get_shape())
print(sess.run(conv_valid))
'''
shape: (1, 1, 1, 1)
value: [[[[12.]]]]
'''

print(conv_same.get_shape())
print(sess.run(conv_same))
'''
shape: (1, 2, 2, 1)
value:    [[[[12.]
[9.]]

[[15.]
[9.]]]]
'''


例子中输入图片大小为 3x3, 卷积尺寸为 2x2, stride 为 2,

VALID
参数的结果
shape
为 1x1,其值为 1x1+1x2+1x4+1x5 = 12, 没有覆盖的点直接略过,如图



SAME
会自动在输入图片下边和右边填充值维0的一行和一列

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: