np.transpose转置函数

2021年1月15日 / 59次阅读 / Last Modified 2021年1月15日
NumPy

矩阵的转置很简单,mxn --> nxm,但如果是3维或3维以上的tensor呢?或者在转置的时候,需要指定axis的顺序呢?np.transpose函数可以干这些事情。

>>> a = np.arange(10).reshape(2,5)
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> a.T
array([[0, 5],
       [1, 6],
       [2, 7],
       [3, 8],
       [4, 9]])
>>> np.transpose(a)
array([[0, 5],
       [1, 6],
       [2, 7],
       [3, 8],
       [4, 9]])

以上是2位矩阵的标准转置动作,注意 a.T这个用法。

3维矩阵的转置:

>>> b = np.arange(60).reshape(3,4,5)
>>> b
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])
>>> b.shape
(3, 4, 5)
>>> b.T.shape
(5, 4, 3)
>>> b.T
array([[[ 0, 20, 40],
        [ 5, 25, 45],
        [10, 30, 50],
        [15, 35, 55]],

       [[ 1, 21, 41],
        [ 6, 26, 46],
        [11, 31, 51],
        [16, 36, 56]],

       [[ 2, 22, 42],
        [ 7, 27, 47],
        [12, 32, 52],
        [17, 37, 57]],

       [[ 3, 23, 43],
        [ 8, 28, 48],
        [13, 33, 53],
        [18, 38, 58]],

       [[ 4, 24, 44],
        [ 9, 29, 49],
        [14, 34, 54],
        [19, 39, 59]]])
>>> np.transpose(b).shape
(5, 4, 3)
>>> np.transpose(b)
array([[[ 0, 20, 40],
        [ 5, 25, 45],
        [10, 30, 50],
        [15, 35, 55]],

       [[ 1, 21, 41],
        [ 6, 26, 46],
        [11, 31, 51],
        [16, 36, 56]],

       [[ 2, 22, 42],
        [ 7, 27, 47],
        [12, 32, 52],
        [17, 37, 57]],

       [[ 3, 23, 43],
        [ 8, 28, 48],
        [13, 33, 53],
        [18, 38, 58]],

       [[ 4, 24, 44],
        [ 9, 29, 49],
        [14, 34, 54],
        [19, 39, 59]]])

可以看出 b.T 的结果与np.transpose(b)的结果一样。

指定axis的转置:

>>> a.shape
(2, 5)
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> np.transpose(a, (0,1)).shape
(2, 5)
>>> np.transpose(a, (0,1))
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> np.transpose(a, (1,0)).shape
(5, 2)
>>>
>>> b.shape
(3, 4, 5)
>>> np.transpose(b, (1,2,0)).shape
(4, 5, 3)
>>> np.transpose(b, (2,0,1)).shape
(5, 3, 4)

axis参数是一个tuple,指定了转之前tensor的axis的一种排列!(numpy模块的很多函数接口都有这个参数,应该都是这个含义)

-- EOF --

本文链接:https://www.pynote.net/archives/3232

留言区

《np.transpose转置函数》有1条留言

您的电子邮箱地址不会被公开。 必填项已用*标注

  • 麦新杰

    np.transpose与np.reshape有根本的不同... [回复]


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top