TensorFlow:使用tf.reshape函數(shù)重塑張量

2018-12-25 11:01 更新

TensorFlow - tf.reshape 函數(shù)

reshape(
    tensor,
    shape,
    name=None
)

參見指南:張量變換>形狀和形狀

重塑張量.

給定tensor,這個操作返回一個張量,它與帶有形狀shape的tensor具有相同的值.

如果shape的一個分量是特殊值-1,則計算該維度的大小,以使總大小保持不變.特別地情況為,一個[-1]維的shape變平成1維.至多能有一個shape的分量可以是-1.

如果shape是1-D或更高,則操作返回形狀為shape的張量,其填充為tensor的值.在這種情況下,隱含的shape元素數(shù)量必須與tensor元素數(shù)量相同.

例如:

# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor 't' has shape [9]
reshape(t, [3, 3]) ==> [[1, 2, 3],
                        [4, 5, 6],
                        [7, 8, 9]]

# tensor 't' is [[[1, 1], [2, 2]],
#                [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2]
reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
                        [3, 3, 4, 4]]

# tensor 't' is [[[1, 1, 1],
#                 [2, 2, 2]],
#                [[3, 3, 3],
#                 [4, 4, 4]],
#                [[5, 5, 5],
#                 [6, 6, 6]]]
# tensor 't' has shape [3, 2, 3]
# pass '[-1]' to flatten 't'
reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]

# -1 can also be used to infer the shape

# -1 is inferred to be 9:
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 2:
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 3:
reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],
                              [2, 2, 2],
                              [3, 3, 3]],
                             [[4, 4, 4],
                              [5, 5, 5],
                              [6, 6, 6]]]

# tensor 't' is [7]
# shape `[]` reshapes to a scalar
reshape(t, []) ==> 7

參數(shù):

  • tensor:一個Tensor.
  • shape:一個Tensor;必須是以下類型之一:int32,int64;用于定義輸出張量的形狀.
  • name:操作的名稱(可選).

返回值:

該操作返回一個Tensor.與tensor具有相同的類型.

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號