Numpy中的axis的很重要,不光np(后文numpy简称np)中的计算很重要,而且在深度学习中的张量计算也经常用到,对这np中axis等矩阵或张量的基本概念的理解很重要。
Numpy中矩阵或多维数组需要理解的概念:
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 non-negative integers. 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.]]
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality
参考:
NumPy quickstart
numpy Quickstart tutorial
在该np数组中,
axis进阶理解,
axis为"[ ]"的层数,最外层为axis=0,即上图红色框所内的元素;axis=1,为绿框中的元素,还包含第二行,第三行。
[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
1 2 3 4
shape为 c.shape
计算规则:
axis=i (0<= i <=N-1)
a=array(
[...[[...[a,b,c]...],
[...[x,y,z]...],
...
[...[1,2,3]...]
]
...
[[...[a,b,c]...],
[...[x,y,z]...],
...
[...[1,2,3]...]
]
])
如上面的例子:
设中间的“[…[[…[]” 中的“…[“为axis=i,axis=i 的length为k,计算np.sum(a, axis=i):
axis=i “[ ]“下的同级别子”[ ]”(下图红框)里的对应元素进行计算, 子”[ ]"length可能大于1。最后的shape等于shape = a.shape, del shape[i]。