tf.pad()


  說一下我理解的tf.pad(),先來看一下定義:

def pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0):

什么意思呢?目的就是對輸入tensor進行擴展,那么擴展的寬度就由paddings來控制了;至於modeconstant_values則表示對tensor擴展時填充的方式。

一維tensor擴展:

import tensorflow as tf

tensor = tf.constant([[1, 2, 3]])
paddings = tf.constant([[1, 2], [3, 4]])
result = tf.pad(tensor, paddings)

with tf.Session() as sess:
    print(sess.run(result))
[[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 2 3 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, 2, 3]](其實還是二維的)四個方向進行擴展,paddings=[[1, 2], [3, 4]]分別就對應着上、下、左、右四個邊界擴展的寬度;

二維tensor擴展:

import tensorflow as tf

tensor = tf.constant([[1, 2], [3, 4]])
paddings = tf.constant([[1, 2], [3, 4]])
result = tf.pad(tensor, paddings)

with tf.Session() as sess:
    print(sess.run(result))
[[0 0 0 0 0 0 0 0 0]
 [0 0 0 1 2 0 0 0 0]
 [0 0 0 3 4 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]]

同上;

三維tensor擴展:

import tensorflow as tf

tensor = tf.constant([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]]) # shape: (2, 2, 3)
paddings = tf.constant([[1, 2], [3, 4], [5, 6]])
result = tf.pad(tensor, paddings)

with tf.Session() as sess:
    print(tensor.shape) # shape: (2, 2, 3)
    print(sess.run(result)) 
    print(result.shape)  # shape: (5, 9, 14)
    

輸出結果如下:

paddings是一個\(3\times 2\)的矩陣,第一行[1, 2]表示對tensor的第一個維度進行擴展;第二行[3, 4]tensor的第二個維度進行擴展;第三行[5, 6]tensor的第三個維度進行擴展;

  可以看到,paddings的要求都是\(N\times 2\)的矩陣,其中\(N\)可能就是與tensor的維度相關了吧。

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

參數mode

tf.pad()方法提供了三種填充tensor的方式:

  • mode="CONSTNAT", constant_values=0: 默認,以常數值0來填充;
  • mode="REFLECT"
  • mode="SYMMETRIC"

不同modetensor的shape有着不同的要求。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM