0
$\begingroup$

I am having a problem trying to reshape my numpy array. i have a 2 dimensional array and i want to make it a 3D array. I have looked everywhere but even if i find some answering my question they just make it complicated. I just want to know is there a mathematical way to calculate reshaping a numpy.

$\endgroup$
0
$\begingroup$

I'm not sure if I fully understand what you mean, but numpy.expand_dims can be used to expand an array at the given index, allowing you to convert a 2 dimensional array to a 3 dimensional array.

import numpy as np

array = np.array([[1,2],[3,4]])
print(array.shape)
# (2, 2)
array = np.expand_dims(array, 0)
print(array.shape)
# (1, 2, 2)
| improve this answer | |
$\endgroup$
  • $\begingroup$ I managed to solve it, let me just answer my own question . $\endgroup$ – Thembekile Mkhombo Apr 11 at 12:17
0
$\begingroup$

I managed to solve the problem, so let me explain it so it all makes sense. So I had a 2D array of shape (76, 5) right, and I wanted to reshape it to a 3D (76, 2, 5) array so i can stick it in to my keras LSTM model. But this is how I was doing it np.reshape(array, (76, 2, 5)), and this gave me the error that looked something like this cannot reshape array of size 380 to array of shape (76, 2, 5). So my confusion lied in the relationship between dimension and size. I than figured out that you could get the size from just knowing the dimension (if you multiply your dimensions you get your size), therefore 76*5 = 380 which is the size and 76*2*5 = 760 which is too big to fit in my old array. In order to reshape my array to become 3D I had to adjust some values

row = int(array.shape[0]/2) #The additional dimension i want to add
array = np.reshape(array, (row, 2, 5))

So now the shape of my array is (38, 2, 5) and the resulting size is now 38*2*5 = 380. So in conclusion if you want to reshape an already existing array, find the size first using the

array.size

Than make sure that the multiplication of the dimensions of the new array that you want is equivalent to the size.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.