Home > OS >  How the shape is (3 2 1) | Numpy |
How the shape is (3 2 1) | Numpy |

Time:11-17

I am learning numpy , have a question in my mind not able to clearly visualise from where this 1 as come in shape

import numpy as np

a = np.array([ [[1],[56]] , [[8],[98]] ,[[89],[62]] ])
np.shape(a)

The output is printed as : (3 ,2 , 1)

Will be appreciated if you could represent in diagrammatic / image format What actually the 1 means in output

CodePudding user response:

Basically, that last 1 is because every number in a has brackets around it.

Formally, it's the length of your "last" or "innermost" dimension. You can take your first two dimensions and arrange a as you would a normal matrix, but note that each element itself has brackets around it - each element is itself an array:

[[ [1] [56]]
 [ [8] [98]]
 [[89] [62]]]

If you add an element to each innermost-array, making that third shape number get larger, it's like stacking more arrays behind this top one in 3d, where now the corresponding elements in the "behind" array are in the same innermost array as the "front" array.

Equivalently, instead of considering the first two indices to denote the regular flat matrices, you can think of the back two making the flat matrices. This is how numpy does it: try printing out an array like this: x = np.random.randint(10, size = (3,3,3)). Along the first dimension, x[0], x[1], and x[2] are printed after each other, and each one individually is formatted like a 3x3 matrix. Then the second index corresponds to the rows of each individual matrix, and the third index corresponds to the columns. Note that when you print a, there's only one column displayed - its third dimension has size 1. You can play with the definition of x to see more what's going on (change the numbers in the size argument).

An alright example of visualizing a 3d array this way is this image, found on the Wikipedia page for the visualization of 3d Levi-Civita symbols

Don't worry too much about what the Levi-Civita symbol actually is - just note that here, if it were a numpy array it would have shape (3,3,3) (like the x I defined above). You use three indices to specify each element, i, j, and k. i tells you the depth (blue, red, or green), j tells you the row, and k tells you the column. When numpy prints, it just lists out blue, red, then green in order.

CodePudding user response:

May be this could help you to understand

Lets break part by part

Example 1 : a=np.array([4]) -> output : (1,) : number of elements : 1

Example 2 : a=np.array([4,5]) -> output : (2,) number of elements : 2

Example 3 : a=np.array([[4],[5]]) -> output : (2,1) : rows : 2 and cols : 1

Example 4 :

a=np.array
( 
    
    [  
    
    [[4],[5]]   ,    
    [[7],[8]]   ,    
    [[11],[10]]  
    
    ]   

)

output : (3,2,1)

Output

  • Related