Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten axes of a multidimensional array without making copies in NumPy?

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.

like image 547
Alexandre Vassalotti Avatar asked Apr 07 '12 05:04

Alexandre Vassalotti


2 Answers

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.

like image 107
senderle Avatar answered Sep 28 '22 02:09

senderle


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.

like image 23
aaren Avatar answered Sep 28 '22 02:09

aaren