What is the difference between np.array and np.stack applied to a list of images

Viewed 169

I have a list containing numpy arrays of identical 2D shape I wanna pack those images for a ConvNet Classifier and I tried two approaches as shown below :

X_train = np.array(lst_imgs).reshape(m, 24, 40, 1)/255
XX_train = np.stack((lst_imgs), -1).reshape(m, 24, 40, 1)/255

both tensors yield shape of : (4828, 24, 40, 1)

However they don't contain the same elements at each index. Can someone please explain to me what is the difference between np.array and np.stack for this purpose and which one is the most suitable ?

Thank you very much !

1 Answers

np.stack and np.array provide exactly the same array, unless you pass a specific axis to the second one.

Let us look at a smaller example on a tiny list of 2d arrays

>>> lst = [i for i in np.arange(8).reshape(2,2,2)]
>>> lst
[array([[0, 1],
       [2, 3]]), array([[4, 5],
       [6, 7]])]

Ok, it is indeed a list of 2 2D arrays each of shape (2,2)

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

       [[4, 5],
        [6, 7]]])
>>> np.stack(lst)
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

Ok, we have the same result

>>> np.stack(lst, -1)
array([[[0, 4],
        [1, 5]],

       [[2, 6],
        [3, 7]]])

But if we stack of the third axis (-1 here means last), we also get a 3D array but with elements in a different order.

Here I cannot know which is the correct order for you use case. I have just explained why you get different results.

Related