numpy.transpose如何在此示例中工作? [英] How does numpy.transpose work for this example?

查看:117
本文介绍了numpy.transpose如何在此示例中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解numpy.transpose的实际工作方式. 例如

I have difficulty understanding how numpy.transpose actually works. For example

a_value = array([[[0, 1],
                  [2, 3]],

                 [[4, 5],
                  [6, 7]]])

当我这样做

np.transpose(a_value, (2, 1, 0))

我知道

array([[[0, 4],
        [2, 6]],

       [[1, 5],
        [3, 7]]])

如何手动导出此转置?在上述情况下,我需要直观地理解公式或步骤,以便可以将其推广到更高的维度.

How can I derive this transpose manually? I need to understand the formula or the steps intuitively in the above case so I can generalize it for higher dimensions.

推荐答案

文档-

numpy.transpose(a, axes=None)

numpy.transpose(a, axes=None)

axes:整数列表,可选 默认情况下,反转尺寸,否则根据给定的值对轴进行排列.

axes : list of ints, optional By default, reverse the dimensions, otherwise permute the axes according to the values given.

第二个参数是用于排列值的轴.例如,如果初始元素的索引为(x,y,z)(其中x为第0轴,y为第1轴,z为第2轴),则该元素在结果数组中的位置变为( z,y,x)(即第2轴,然后是第1轴,最后是第0轴),基于您为axes提供的参数.

The second argument is the axes using which the values are permuted. That is for example if the index of initial element is (x,y,z) (where x is 0th axes, y is 1st axes, and z is 2nd axes) , the position of that element in the resulting array becomes (z,y,x) (that is 2nd axes first, then 1st axes, and last 0th axes) , based on the argument you provided for axes .

由于要转置形状为(2,2,2)的数组,因此转置后的形状也为(2,2,2),并且位置将更改为-

Since you are transposing an array of shape (2,2,2) , the transposed shape is also (2,2,2) , and the positions would change as -

(0,0,0) -> (0,0,0)
(1,0,0) -> (0,0,1)
(0,1,0) -> (0,1,0)
(1,1,0) -> (0,1,1)
...


由于您选择的轴是微不足道的,因此请为其他轴进行说明.示例-


Since the axes you choose are trivial, lets explain this for another axes. Example -

In [54]: A = np.arange(30).reshape((2, 3, 5))
In [55]: A
Out[55]:
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]]])

In [56]: np.transpose(A,(1,2,0))
Out[56]:
array([[[ 0, 15],
        [ 1, 16],
        [ 2, 17],
        [ 3, 18],
        [ 4, 19]],

       [[ 5, 20],
        [ 6, 21],
        [ 7, 22],
        [ 8, 23],
        [ 9, 24]],

       [[10, 25],
        [11, 26],
        [12, 27],
        [13, 28],
        [14, 29]]])

这里,第一个元素(0,0,0)成为结果中的(0,0,0)元素.

Here, the first element (0,0,0) becomes the (0,0,0) element in the result.

第二个元素(0,0,1)成为结果中的(0,1,0)元素.依此类推-

The second element (0,0,1) becomes the (0,1,0) element in the result. And so on -

(0,0,0) -> (0,0,0)
(0,0,1) -> (0,1,0)
(0,0,2) -> (0,2,0)
...
(2,3,4) -> (3,4,2)
...

这篇关于numpy.transpose如何在此示例中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆