When to use .shape and when to use .reshape?

I ran into a memory issue while trying to use .reshape

numpy in an array and figured out if I could somehow modify the array in place, which would be great.

I figured out that I can resize the array just by changing the value .shape

. Unfortunately, when I tried to use .shape

, I got a memory error again, which made me think it hadn't changed in place.

I was wondering when do I use it, when do I use another one?

Any help is appreciated.

If you would like more information, please let me know.

EDIT:

I added my code and how the matrix I want to change is generated in case it matters.

Change the N value depending on your memory.

import numpy as np
N = 100
a = np.random.rand(N, N)
b = np.random.rand(N, N)
c = a[:, np.newaxis, :, np.newaxis] * b[np.newaxis, :, np.newaxis, :]
c = c.reshape([N*N, N*N])
c.shape = ([N, N, N, N])

      

EDIT2: This is the best view. Apparently, transposition is important because it changes arrays from C-adjacent to F-adjacent, and the resulting multiplication is adjacent in the above case, while it is not in the following.

import numpy as np
N = 100
a = np.random.rand(N, N).T
b = np.random.rand(N, N).T
c = a[:, np.newaxis, :, np.newaxis] * b[np.newaxis, :, np.newaxis, :]
c = c.reshape([N*N, N*N])
c.shape = ([N, N, N, N])

      

+3


source to share


1 answer


numpy.reshape

will copy the data if it cannot make the correct look, whereas the installation shape

will result in a data copy error.



It is not possible to reshape an array without copying the data. If you want the error to be raised if the data is copied, you must assign the new shape to the shape attribute of the array.

+6


source







All Articles