tf.pad()

转: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 ofinputin 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:

  1. # 't' is [[ 1, 1], [ 2, 2]]
  2. # 'paddings' is [[ 1, 1]], [ 2, 2]]
  3. # rank of 't' is 2
  4. pad(t, paddings) ==> [[ 0, 0, 0, 0, 0]
  5. [ 0, 0, 0, 0, 0]
  6. [ 0, 1, 1, 0, 0]
  7. [[ 0, 2, 2, 0, 0]
  8. [ 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]]

  1. input = [[ 1], [ 2], [ 3]]
  2. padding = [[ 1, 2],[ 1, 2]]
  3. print(sess.run(tf.pad(input,padding)))
  4. [[ 0 0 0 0]
  5. [ 0 1 0 0]
  6. [ 0 2 0 0]
  7. [ 0 3 0 0]
  8. [ 0 0 0 0]
  9. [ 0 0 0 0]]
由输出tensor可以看出, 输入input从外到内为2层,padding的 [1,1]代表在最外层上进行,表示在原input前加一行全0,后加2行全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

  1. input = [[ 1], [ 2], [ 3]]
  2. padding = [[ 3, 1],[ 3, 5]]
  3. print(sess.run(tf.pad(input,padding)))
  4. [[ 0 0 0 0 0 0 0 0 0]
  5. [ 0 0 0 0 0 0 0 0 0]
  6. [ 0 0 0 0 0 0 0 0 0]
  7. [ 0 0 0 1 0 0 0 0 0]
  8. [ 0 0 0 2 0 0 0 0 0]
  9. [ 0 0 0 3 0 0 0 0 0]
  10. [ 0 0 0 0 0 0 0 0 0]]

猜你喜欢

转载自blog.csdn.net/sinat_39372048/article/details/80976722
tf