TensorFlow的reshape操作 tf.reshape的實現
阿新 • • 發佈:2020-04-20
初學tensorflow,如果寫的不對的,請更正,謝謝!
tf.reshape(tensor,shape,name=None)
函式的作用是將tensor變換為引數shape的形式。
其中shape為一個列表形式,特殊的一點是列表中可以存在-1。-1代表的含義是不用我們自己指定這一維的大小,函式會自動計算,但列表中只能存在一個-1。(當然如果存在多個-1,就是一個存在多解的方程了)
好了我想說的重點還有一個就是根據shape如何變換矩陣。其實簡單的想就是,
reshape(t,shape) => reshape(t,[-1]) => reshape(t,shape)
首先將矩陣t變為一維矩陣,然後再對矩陣的形式更改就可以了。
官方的例子:
# tensor 't' is [1,2,3,4,5,6,7,8,9] # tensor 't' has shape [9] reshape(t,[3,3]) ==> [[1,3],[4,6],[7,9]] # tensor 't' is [[[1,1],[2,2]],# [[3,4]]] # tensor 't' has shape [2,2] reshape(t,4]) ==> [[1,1,2],4]] # tensor 't' is [[[1,# [2,# [4,4]],# [[5,5],# [6,6]]] # tensor 't' has shape [3,3] # pass '[-1]' to flatten 't' reshape(t,[-1]) ==> [1,6] # -1 can also be used to infer the shape # -1 is inferred to be 9: reshape(t,-1]) ==> [[1,6]] # -1 is inferred to be 2: reshape(t,[-1,9]) ==> [[1,6]] # -1 is inferred to be 3: reshape(t,[ 2,-1,3]) ==> [[[1,3]],[[4,4],[5,[6,6]]] # tensor 't' is [7] # shape `[]` reshapes to a scalar reshape(t,[]) ==> 7
在舉幾個例子或許就清楚了,有一個數組z,它的shape屬性是(4,4)
z = np.array([[1,8],[9,10,11,12],[13,14,15,16]]) z.shape (4,4)
z.reshape(-1)
z.reshape(-1) array([ 1,9,12,13,16])
z.reshape(-1,1)
也就是說,先前我們不知道z的shape屬性是多少,但是想讓z變成只有一列,行數不知道多少,通過`z.reshape(-1,1)`,Numpy自動計算出有12行,新的陣列shape屬性為(16,1),與原來的(4,4)配套。
z.reshape(-1,1) array([[ 1],[ 2],[ 3],[ 4],[ 5],[ 6],[ 7],[ 8],[ 9],[10],[11],[12],[13],[14],[15],[16]])
z.reshape(-1,2)
newshape等於-1,列數等於2,行數未知,reshape後的shape等於(8,2)
z.reshape(-1,2) array([[ 1,[ 3,[ 5,[ 7,[ 9,10],[11,14],[15,16]])
到此這篇關於TensorFlow的reshape操作 tf.reshape的實現的文章就介紹到這了,更多相關TensorFlow的reshape操作 tf.reshape內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!