Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy ndarray shape with 3 parameters

I am confused about what is the shape of ndarray when 3 parameters are provided:

For example, what is the difference between:

np.zeros((2, 1, 3))
array([[[ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.]]])

and:

np.zeros((1, 2, 3))
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

It seems to me that both of them represent 2*3 matrices.

like image 805
user2505650 Avatar asked Jan 31 '18 10:01

user2505650


People also ask

How do I create a NumPy 3 dimensional array?

Importing the NumPy package enables us to use the array function in python. To create a three-dimensional array, we pass the object representing x by y by z in python, where x is the nested lists in the object, y is the nested lists inside the x nested lists, and z is the values inside each y nested list.

Why do we do reshape (- 1 1?

If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).

Which method can change the shape of Ndarray?

The shape of the array can also be changed using the resize() method.


1 Answers

No, the shapes are different, you have to pay attention to the square brackets:

>>> np.zeros((2, 1, 3))
array([[[ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.]]])

versus:

>>> np.zeros((1, 2, 3))
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

as you can see, in the first call, we have two times a pair of square brackets for the second dimension, whereas in the latter, we only have one such pair.

The shape is also different:

>>> np.zeros((2, 1, 3)).shape
(2, 1, 3)
>>> np.zeros((1, 2, 3)).shape
(1, 2, 3)

So in the former we have a list that contains two sublists. Each of these sublists contains one element: a list of three elements. In the latter we have a list with one element: a sublist with two elements, and these two elements are lists with three elements.

So a vanilla Python list equivalent would be:

[ [ [0, 0, 0] ], [ [0, 0, 0] ] ]

versus:

[ [ [0, 0, 0], [0, 0, 0] ] ]
like image 123
Willem Van Onsem Avatar answered Sep 29 '22 08:09

Willem Van Onsem