I am wondering if there is a way to flatten a multidimensional array (i.e., of type ndarray
) along given axes without making copies in NumPy. For example, I have an array of 2D images and I wish to flatten each to a vector. So, one easy way to do it is numpy.array([im.flatten() for im in images])
, but that creates copies of each.
ravel
it:
>>> a = numpy.arange(25).reshape((5, 5))
>>> b = a.ravel()
>>> b[0] = 55
>>> a
array([[55, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
Or reshape
it:
>>> a = numpy.arange(27).reshape((3, 3, 3))
>>> b = a.reshape((9, 3))
>>> b[0] = 55
>>> a
array([[[55, 55, 55],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
Under most circumstances, these both return a view of the original array, rather than a copy.
If you don't know the shape of your input array:
images.reshape((images.shape[0], -1))
-1
tells reshape to work out the remaining dimensions. This assumes that you
want to flatten the first axis of images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With