Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array reshape adding dimension

Ok I am a (very) novice Python user, but I am trying to translate a piece of Python code into R, and I have run into a confusing problem with array reshaping.

Lets make some example data:

X1 = np.array([[-0.047, -0.113, 0.155, 0.001],
        [0.039, 0.254, 0.054, 0.201]], dtype=float)

In:X1
Out:
array([[-0.047, -0.113, 0.155, 0.001],
        [0.039, 0.254, 0.054, 0.201]])
In:X1.shape
Out: (2,4)

Ok so I've made a 2D array with 2 rows and 4 columns. I'm happy with this. The confusion arises with this line of code:

X2 = X1.reshape((2, -1, 1))

In: X2
Out:
array([[[-0.047],
        [-0.113],
         [0.155],
         [0.001]],

         [0.039],
         [0.254],
         [0.054],
         [0.201]]])

In: X2.shape
Out: (2, 4, 1)

So I know that I have added an extra dimension (which I think is the 3rd digit 1 in the reshape command), but I don't understand what else this had done. The shape implies it is still got 2 rows and 4 columns, but clearly something else is changed. Again my motivation here is to do the same operation in R, but until I know I understand what I've transformed here I am stuck. (Forgive me if this is an awful question I only started Python yesterday!)

like image 339
user2498193 Avatar asked Jan 25 '17 12:01

user2498193


1 Answers

By reshape(2, -1, 1) you have not just added added a new dimension. You have said

* the 1st dimension should be of size 2
* the 3rd dimension should be of size 1
* the 2nd should be whatever remains

so, the only valid option if 4. If you just want to add a new dimension to an existing matrix, you should do something like x[:, np.newaxis, :] (exact usage depends on what you want the output format to be)

like image 195
blue_note Avatar answered Sep 28 '22 08:09

blue_note