转:https://blog.csdn.net/banana1006034246/article/details/76585355
说明:关于 tf.pad(...) 函数网上的解释和官网都让你看不懂,自己理解整理如下,希望可以帮到需要的人,以下内容只关注0扩展边界
函数原型:
tf.pad(input, paddings, name=None)
input : 代表输入张量
padding : 代表加的边界
name : 代表此操作的名字
官方的doc为: 可以访问 tensorflow API
Pads a tensor with zeros.
This operation pads a input
with zeros according to the paddings
youspecify.paddings
is an integer tensor with shape[Dn, 2]
, where n is therank ofinput
. For each dimension D ofinput
,paddings[D, 0]
indicateshow many zeros to add before the contents ofinput
in that dimension, andpaddings[D, 1]
indicates how many zeros to add after the contents ofinput
in that dimension.
The padded size of each dimension D of the output is:
paddings(D, 0) + input.dim_size(D) + paddings(D, 1)
For example:
-
# 't' is [[ 1, 1], [ 2, 2]]
-
# 'paddings' is [[ 1, 1]], [ 2, 2]]
-
# rank of 't' is 2
-
pad(t, paddings) ==> [[ 0, 0, 0, 0, 0]
-
[ 0, 0, 0, 0, 0]
-
[ 0, 1, 1, 0, 0]
-
[[ 0, 2, 2, 0, 0]
-
[ 0, 0, 0, 0, 0]]
以上的文档是不是看了也没法理解是啥意思
padding它必须是 [N, 2] 形式,N代表张量的阶, 2代表必须是2列,比如
padding = [ [1,1], [2,2] ] 或者
padding = [ [1,1], [2,2], [3,3] ]
具体根据需要设定,但列必须为2,不然报错
首先,假定 一个3x1的一个张量input = [[1],[2],[3]] , padding = [[1,1], [2,2]]
-
input = [[ 1], [ 2], [ 3]]
-
padding = [[ 1, 2],[ 1, 2]]
-
print(sess.run(tf.pad(input,padding)))
-
[[ 0 0 0 0]
-
[ 0 1 0 0]
-
[ 0 2 0 0]
-
[ 0 3 0 0]
-
[ 0 0 0 0]
-
[ 0 0 0 0]]
[ [0 0 ]
[0 1 ]
[0 2 ]
[0 3 ]
[0 0 ]
[0 0 ] ]
然后,padding的[1,2]代表在第二层上操作,在每一行的前面加一个0,在末尾加2个0,得到最终的输出结果
[[ 0 0 0 0 0 ]
[ 0 0 1 0 0 ]
[ 0 0 2 0 0 ]
[ 0 0 3 0 0 ]
[ 0 0 0 0 0 ]
[ 0 0 0 0 0 ]]
其他维的操作也是类似,padding里面每个[a, b] 都代表在相应的维上,前加 a个(行) 0,后加b个(行) 0
在看一个例子:第一个维度上前加3行0,后加1行0;第二维度上,前加3个0,后加5个0
-
input = [[ 1], [ 2], [ 3]]
-
-
padding = [[ 3, 1],[ 3, 5]]
-
print(sess.run(tf.pad(input,padding)))
-
[[ 0 0 0 0 0 0 0 0 0]
-
[ 0 0 0 0 0 0 0 0 0]
-
[ 0 0 0 0 0 0 0 0 0]
-
[ 0 0 0 1 0 0 0 0 0]
-
[ 0 0 0 2 0 0 0 0 0]
-
[ 0 0 0 3 0 0 0 0 0]
-
[ 0 0 0 0 0 0 0 0 0]]