当前位置: 移动技术网 > IT编程>脚本编程>Python > numpy的axis的理解和检验

numpy的axis的理解和检验

2018年08月12日  | 移动技术网IT编程  | 我要评论

侧柏叶泡酒比例,蓝蓝游戏网,沐语人生

原文: 

一、官网的定义:

https://docs.scipy.org/doc/numpy/user/quickstart.html

In NumPy dimensions are called axes.

For example, the coordinates of a point in 3D space [1, 2, 1] has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.

[[ 1., 0., 0.],
 [ 0., 1., 2.]]

其实,可以这么理解。维度(dimension) D和数组A,D[axis]和A[i] 。是不是大概懂了,axis对应第几维度,与数组的下标的作用差不多。但是axis有点区别的。既然axis是下标那么就有范围:

[-维度,维度),如上例子axis的取值范围 [-2,2),记住不包括2。

维度与axis的对应关系:axis是从最外层的 [] 数起来的,如上的例子,axis=0:第二维,axis=1:第一维。

二、验证:

1 # 产生24个[0,50)的随机整数,维度为3
2 x = np.random.RandomState(5).randint(50, size=[2, 3, 4])
3 print(x.ndim, x.shape, x.size)
4 print("x:\n", x)

选一个能够使用到axis的函数:这里选用numpy.amax()(选出最大的元素),https://docs.scipy.org/doc/numpy/reference/generated/numpy.amax.html#numpy.amax

为了方便理解,先从最内层开始

1 print("x[0][0]:\n", x[0][0])
2 print("axis=2: \n", np.amax(x, 2))

 

print("x[0]:\n", x[0])
print("axis=1: \n", np.amax(x, 1))

 

1 print("x:\n", x)
2 print("axis=0: \n", np.amax(x, 0))

很显然,从axis=2,axis=1都挺好理解,但是axis=0就有点困惑了,而且这个仅仅是三维而已,那么四维、五维呢。

但是其实仔细观察axis=2的第一个数字54是怎么来的呢?是从x[0][0][0]—x[0][0][4]比较而得。因此一共有3*4个。

同理axis=1时,比较的就是:x[0][0][0]—x[0][3][0]共3*5个

同理axis=2时,比较的是:x[0][0][0]—x[2][0][0],共4*5个

现在,是不是就对不同的axis的输出的形状或者说排列有一定的了解了?而且是不是体会到axis的作用了?我可是烦死那么多方括号了!!

 三、总结

最直观的:函数所选的axis的值,就表明 x[][][] 的第几个方块号,从0开始,代表第一个[ ],即x[ ] [ ] [ ]

不足或者错误之处,欢迎指正!

 1 import numpy as np
 2 
 3 # 产生60个[0,60)的随机整数,维度为3
 4 x = np.random.RandomState(5).randint(60, size=[3, 4, 5])
 5 print(x.ndim, x.shape, x.size)
 6 print("x:\n", x)
 7 print("x[0][0]:\n", x[0][0])
 8 print("axis=2: \n", np.amax(x, 2))
 9 
10 print("x[0]:\n", x[0])
11 print("axis=1: \n", np.amax(x, 1))
12 
13 print("x:\n", x)
14 print("axis=0: \n", np.amax(x, 0))
15 print("\n", np.amin(x, 0))
16 for i in range(4):
17     print(x[0][i][1])
全部代码

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网