簡體   English   中英

Tensorflow Tensor重塑並用零填充

[英]Tensorflow Tensor reshape and pad with zeros

有沒有辦法重塑張量並用零填充任何溢出? 我知道ndarray.reshape會這樣做,但據我所知,將Tensor轉換為ndarray需要在GPU和CPU之間進行翻轉。

Tensorflow的reshape()文檔說TensorShapes需要具有相同數量的元素,所以最好的方法可能是pad()然后reshape()?

我正在努力實現:

a = tf.Tensor([[1,2],[3,4]])
tf.reshape(a, [2,3])
a => [[1, 2, 3],
      [4, 0 ,0]]

據我所知,沒有內置的運算符可以做到這一點(如果形狀不匹配, tf.reshape()會給你一個錯誤)。 但是,您可以通過幾個不同的運算符實現相同的結果:

a = tf.constant([[1, 2], [3, 4]])

# Reshape `a` as a vector. -1 means "set this dimension automatically".
a_as_vector = tf.reshape(a, [-1])

# Create another vector containing zeroes to pad `a` to (2 * 3) elements.
zero_padding = tf.zeros([2 * 3] - tf.shape(a_as_vector), dtype=a.dtype)

# Concatenate `a_as_vector` with the padding.
a_padded = tf.concat([a_as_vector, zero_padding], 0)

# Reshape the padded vector to the desired shape.
result = tf.reshape(a_padded, [2, 3])

Tensorflow現在提供pad函數,它以多種方式在張量上執行填充(如opencv2的數組填充函數): https ://www.tensorflow.org/api_docs/python/tf/pad

tf.pad(tensor, paddings, mode='CONSTANT', name=None)

來自上述文檔的示例:

# 't' is [[1, 2, 3], [4, 5, 6]].
# 'paddings' is [[1, 1,], [2, 2]].
# rank of 't' is 2.
pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],
                                  [0, 0, 1, 2, 3, 0, 0],
                                  [0, 0, 4, 5, 6, 0, 0],
                                  [0, 0, 0, 0, 0, 0, 0]]

pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4],
                                 [3, 2, 1, 2, 3, 2, 1],
                                 [6, 5, 4, 5, 6, 5, 4],
                                 [3, 2, 1, 2, 3, 2, 1]]

pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2],
                                   [2, 1, 1, 2, 3, 3, 2],
                                   [5, 4, 4, 5, 6, 6, 5],
                                   [5, 4, 4, 5, 6, 6, 5]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM