tensorflow中的pad函数解释

说明:关于 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 of input. For each dimension D of input,paddings[D, 0] indicateshow many zeros to add before the contents of input in that dimension, and paddings[D, 1] indicates how many zeros to add after the contents of input 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]]

由输出tensor可以看出, 输入input从外到内为2层,padding的 [1,2]代表在最外层上进行,表示在原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

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]]

 

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值