Tensorflow中reshape()函數的使用

初學tensorflow,如果不對請指正,謝謝
tenorflow中有一個函數叫reshape()函數,這個函數可以將輸入的tensor變換成shape的格式。具體看函數說明:

def reshape(tensor, shape, name=None):
  Reshapes a tensor.

  Given `tensor`, this operation returns a tensor that has the same values
  as `tensor` with shape `shape`.

  If one component of `shape` is the special value -1, the size of that dimension
  is computed so that the total size remains constant.  In particular, a `shape`
  of `[-1]` flattens into 1-D.  At most one component of `shape` can be -1.

  If `shape` is 1-D or higher, then the operation returns a tensor with shape
  `shape` filled with the values of `tensor`. In this case, the number of elements
  implied by `shape` must be the same as the number of elements in `tensor`.

1.給定一個tensor,怎麼確定它的shape。
2.給定一個tensor和shape,經過reshape(tensor,shape)變換後返回的tensor是什麼格式的。
先看一看文檔中給出的例子:

For example:

  ```prettyprint
  # 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]

首先,tensor的維數與shape中元素的個數是相等的;其次,shape中數字的乘積與tensor中元素的個數相等,因此在調用reshape()函數時應注意元素個數保持一致。要確定給定的tensor的shape,應該從外往裏看。例如

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

經過reshape變化的t,最外層包含兩個元素,裏面一層包含4個元素,相當於2維數組。變化之前的t,最外層包含兩個元素(第一行末尾一個逗號隔開),中間層每層兩個元素(第一行中間一個逗號隔開),最內層兩個元素,相當於三維數組。
給定了tensor和shape後,將tensor按一維展開,再按照給定的shape重新組合。
如果shape中有-1,函數會自動計算維度,但只能有有個-1.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章