1. 程式人生 > >tensorflow中的pad函式解釋

tensorflow中的pad函式解釋

from:

說明:關於 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:

# '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,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

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]]
---------------------  
作者:banana10060342  
來源:CSDN  
原文:https://blog.csdn.net/banana1006034246/article/details/76585355  
版權宣告:本文為博主原創文章,轉載請附上博文連結!