tf.transpose()函數

來源:互聯網
上載者:User

tensorflow裡面許多針對數組操作的函數,官方文檔又看了沒啥卵用,網上文章直接copy官方文檔而不解釋,只能自己寫個程式測試理解,以3個維度tensor進行理解

tf.transpose()作為數組的轉置函數,原型如下:

def transpose(a, perm=None, name="transpose"):  """Transposes `a`. Permutes the dimensions according to `perm`.

a:是傳入的數組

perm:控制轉置的操作,以perm = [0,1,2] 3個維度數組為例, 0--代表的是最外層的一維, 1--代表外向內數第二維, 2--代表最內層的一維,這種perm是預設的值.現在以如下輸入數組來理解這個函數和參數perm

input_x = [    [        [1, 2, 3, 4],        [5, 6, 7, 8],        [9, 10, 11, 12]    ],    [        [13, 14, 15, 16],        [17, 18, 19, 20],        [21, 22, 23, 24]    ]]

input_x 是一個 2x3x4的一個tensor, 假設perm = [1,0,2], 就是將最外2層轉置,得到tensor應該是  3x2x4的一個張量,將input_x抽象化,不管第3維度

[

     [

          A,

          B,

          C

     ],

     [

          D,

          E,

          F,

     ]

]

變成2x3的tensor,類似於2x3的數組

[

     A  B  C

     D  E  F

]

轉置變成 3x2的數組

[

    A  D

    B  E

    C  F

]

再將A-F換成具體的值,最終得到的張量是

[

  [

     [ 1  2  3  4]
     [13 14 15 16]

 ]
 [

    [ 5  6  7  8]
    [17 18 19 20]

  ]
  [

     [ 9 10 11 12]
     [21 22 23 24]

  ]

]

這就可以看出perm前兩列交換的作用

如果 perm=[0,2,1]說明要交換內層裡面的兩個維度,從原來的2x3x4變成2x4x3的張量,就不抽象化了,結果就是

[

  [

      [ 1  5  9]
      [ 2  6 10]
      [ 3  7 11]
      [ 4  8 12]

  ]

  [

     [13 17 21]
     [14 18 22]
     [15 19 23]
     [16 20 24]

  ]

]

下面貼出My Code:

import tensorflow as tfinput_x = [    [        [1, 2, 3, 4],        [5, 6, 7, 8],        [9, 10, 11, 12]    ],    [        [13, 14, 15, 16],        [17, 18, 19, 20],        [21, 22, 23, 24]    ]]result = tf.transpose(input_x, perm=[0, 2, 1])with tf.Session() as sess:    print(sess.run(result))

注意,使用print(result)只會列印tensor的name  shape  dtype資訊

Tensor("transpose:0", shape=(2, 4, 3), dtype=int32)

想要打出數組的形式,使用session

result = tf.transpose(input_x, perm=[0, 2, 1])print(result)with tf.Session() as sess:    print(sess.run(result))








聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.