One easy way to explain axis is: "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 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."
However, I found it quite difficult to understand what is the result from sum(axis=0), sum(axis=1) and sum(axis=2) etc. Here I would like to provide some examples to show what is the concept of Axis.
If we run:
>> a=np.arange(10);
>> a.resize([2,5]);
Then a is: array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]), a.shape = (2,5)
Here, the axis=0 has a length of 2, axis=1 has a length of 5.
If we run:
>> b=np.arange(24);
>> b.resize([2,3,4]);
Then b's axis=0 has length 2, axis=1 has length 3, axis = 2 has length 4.
The axis is like a internal-index for each entry, to find each entry, such as b[1][2][3] or b[1,2,3], one need to go through (0's axis value = 1, 1's axis value = 2, 3's axis value = 3). So If we want to carry out a sum over specific axis, what we are doing is to "reduce" the axis.
For array a, if we run '' >> a.sum(axis=0) '', then we collapse the 0's axis, and generate a new array with new.shape = (5,), because 0's axis was removed, the 1's axis moves up to serve as 0's axis.
If we run '' >> a.sum(axis=1) '', then we collapse the 1's axis, and generate a new array with new.shape = (2,), because 1's axis was removed, and only 0's axis is left.
For array b, if '' >> b.sum(axis=0) '', then 0's axis was collapsed and 1's axis => 0's axis, and 2's axis => 1's axis, so new.shape = (3,4).
If '' >> b.sum(axis = 1) '', then values aggregates over axis=1 level, and then 1's axis was removed, and 2's axis changed into 1's axis.
If '' >> b.sum(axis=2) '', then 2's axis was collapsed and aggregated accordingly, then the new.shape = (2,3).
Now this is quite clear what the "axis=?" option appears over many build-in functions, it is used to "select the axis to collapse & act on".
No comments:
Post a Comment