numpy的axis的理解和检验

原文:https://www.cnblogs.com/ppes/p/9461246.html 

NumPy's main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes. The number of axes is rank.

一、官网的定义:

For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3. In the example pictured below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

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

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

In NumPy dimensions are called axes.

ndarray.ndim

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.

数组轴的个数,在python的世界中,轴的个数被称作秩

[[ 1., 0., 0.],
 [ 0., 1., 2.]]
>> X = np.reshape(np.arange(24), (2, 3, 4))
  # 也即 2 行 3 列的 4 个平面(plane)
>> X
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]]])

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

shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。

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

shape(x)

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

(2,3,4)

二、验证:

shape(x)[0]

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)

2

图片 1

或者

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

x.shape[0]

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

2

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

再来分别看每一个平面的构成:

图片 2

>> X[:, :, 0]
array([[ 0, 4, 8],
    [12, 16, 20]])
>> X[:, :, 1]
array([[ 1, 5, 9],
    [13, 17, 21]])
>> X[:, :, 2]
array([[ 2, 6, 10],
    [14, 18, 22]])
>> X[:, :, 3]
array([[ 3, 7, 11],
    [15, 19, 23]])

 

也即在对 np.arange(24)(0, 1, 2, 3, ..., 23) 进行重新的排列时,在多维数组的多个轴的方向上,先分配最后一个轴(对于二维数组,即先分配行的方向,对于三维数组即先分配平面的方向)

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

reshpae,是数组对象中的方法,用于改变数组的形状。

 图片 3

二维数组

本文由金沙官网线上发布于编程,转载请注明出处:numpy的axis的理解和检验

您可能还会对下面的文章感兴趣: