Skip to content

Tensorflow 中关于 pad 函数的详细理解

https://blog.csdn.net/u011012422/article/details/77948084

文档的内容

python
"""
  `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of
  `tensor`.
  For each dimension D of `input`, `paddings[D, 0]` indicates how
  many values to add before the contents of `tensor` in that dimension, and
  `paddings[D, 1]` indicates how many values to add after the contents of
  `tensor` in that dimension.
"""
# 't' is [[1, 2, 3], [4, 5, 6]].
# 'paddings' is [[1, 1,], [2, 2]].
# 'constant_values' is 0.
# rank of 't' is 2.
pad(t, paddings, "CONSTANT") ==>
[[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 2, 3, 0, 0],
 [0, 0, 4, 5, 6, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]


pad(t, paddings, "REFLECT") ==>
[[6, 5, 4, 5, 6, 5, 4],
 [3, 2, 1, 2, 3, 2, 1],
 [6, 5, 4, 5, 6, 5, 4],
 [3, 2, 1, 2, 3, 2, 1]]


pad(t, paddings, "SYMMETRIC") ==>
[[2, 1, 1, 2, 3, 3, 2],
 [2, 1, 1, 2, 3, 3, 2],
 [5, 4, 4, 5, 6, 6, 5],
 [5, 4, 4, 5, 6, 6, 5]]

理解思路

tf.pad 的使用,第一个是填充 0,后面两个是复制前几行或者列

[1,1],[2,2]

[1,1] 指的是向上扩充一行,向下扩充一行 [2,2] 指的是向左扩充 2 列,向右扩充 2 列

1. CONSTANT 模式,按上下左右填充几行或者几列的 0

paddings=[[1,1],[2,2]] 的意思是向上填充一行 0,向下填充一行 0,向左填充二行 0,向右填充两行 0

向上填充一行 0,变成

0,0,0 1,2,3 4,5,6

向下填充一行 0

0,0,0 1,2,3 4,5,6 0,0,0

向左填充二行 0

0,0,0,0,0 0,0,1,2,3 0,0,4,5,6 0,0,0,0,0

向右填充两行 0

0,0,0,0,0,0,0 0,0,1,2,3,0,0 0,0,4,5,6,0,0 0,0,0,0,0,0,0

2. REFLECT 模式,首先要定好边缘(可理解为对称轴),按边缘翻(边缘不复制)

比如刚开始

1, 2, 3 4, 5, 6

向上翻一行,以 123 为对称轴

4,5,6 1,2,3 4,5,6

向下翻一行,以 4,5,6 为对称轴

4,5,6 1,2,3 4,5,6 1,2,3

以列 4,1,4,1 为对称轴,向左翻二行

6,5,4,5,6 3,2,1,2,3 6,5,4,5,6 3,2,1,2,3

以列 6,3,6,3 为对称轴,向右翻 2 行

6,5,4,5,6,5,4 3,2,1,2,3,2,1 6,5,4,5,6,5,4 3,2,1,2,3,2,1

3. SYMMETRIC 类似的,唯一的区别是把边缘(也就是对称轴)也复制了,从对称轴开始复制

比如刚开始

1, 2, 3 4, 5, 6

向上翻一行,以 123 为对称轴,从对称轴开始复制

1,2,3 1,2,3 4,5,6

向下翻一行,以 4,5,6 为对称轴

1,2,3 1,2,3 4,5,6 4,5,6

以列 1,1,4,4 为对称轴,向左翻二行

2,1,1,2,3 2,1,1,2,3 5,4,4,5,6 5,4,4,5,6

以列 3,3,6,6 为对称轴,向右翻 2 行

2,1,1,2,3,3,2 2,1,1,2,3,3,2 5,4,4,5,6,6,5 5,4,4,5,6,6,5

Released under the MIT License.