Issue
I ran into a memory problem when trying to use .reshape
on a numpy array and figured if I could somehow reshape the array in place that would be great.
I realised that I could reshape arrays by simply changing the .shape
value.
Unfortunately when I tried using .shape
I again got a memory error which has me thinking that it doesn't reshape in place.
I was wondering when do I use one when do I use the other?
Any help is appreciated.
If you want additional information please let me know.
EDIT:
I added my code and how the matrix I want to reshape is created in case that is important.
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 a better representation. Apparently the transpose seems to be important as it changes the arrays from C-contiguous to F-contiguous, and the resulting multiplication in above case is contiguous while in the one below it is not.
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])
Solution
numpy.reshape
will copy the data if it can't make a proper view, whereas setting the shape
will raise an error instead of copying the data.
It is not always possible to change the shape of an array without copying the data. If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array.
Answered By - ryanpattison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.