Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy broadcast from first dimension

Tags:

python

numpy

In NumPy, is there an easy way to broadcast two arrays of dimensions e.g. (x,y) and (x,y,z)? NumPy broadcasting typically matches dimensions from the last dimension, so usual broadcasting will not work (it would require the first array to have dimension (y,z)).

Background: I'm working with images, some of which are RGB (shape (h,w,3)) and some of which are grayscale (shape (h,w)). I generate alpha masks of shape (h,w), and I want to apply the mask to the image via mask * im. This doesn't work because of the above-mentioned problem, so I end up having to do e.g.

mask = mask.reshape(mask.shape + (1,) * (len(im.shape) - len(mask.shape)))

which is ugly. Other parts of the code do operations with vectors and matrices, which also run into the same issue: it fails trying to execute m + v where m has shape (x,y) and v has shape (x,). It's possible to use e.g. atleast_3d, but then I have to remember how many dimensions I actually wanted.

like image 484
nneonneo Avatar asked Mar 24 '14 07:03

nneonneo


People also ask

Can you broadcast more than 1 dimension?

The arrays can be broadcast together iff they are compatible with all dimensions. After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays.

How do I broadcast a function in NumPy?

NumPy's broadcasting rule relaxes this constraint when the arrays' shapes meet certain constraints. The simplest broadcasting example occurs when an array and a scalar value are combined in an operation: >>> a = np. array([1.0, 2.0, 3.0]) >>> b = 2.0 >>> a * b array([2., 4., 6.])

Does NumPy have broadcasting?

Broadcasting is the name given to the method that NumPy uses to allow array arithmetic between arrays with a different shape or size. Although the technique was developed for NumPy, it has also been adopted more broadly in other numerical computational libraries, such as Theano, TensorFlow, and Octave.

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


2 Answers

how about use transpose:

(a.T + c.T).T
like image 161
HYRY Avatar answered Sep 18 '22 05:09

HYRY


Indexing with np.newaxis creates a new axis in that place. Ie

xyz = #some 3d array
xy = #some 2d array
xyz_sum = xyz + xy[:,:,np.newaxis]
or
xyz_sum = xyz + xy[:,:,None]

Indexing in this way creates an axis with shape 1 and stride 0 in this location.

like image 41
Eelco Hoogendoorn Avatar answered Sep 18 '22 05:09

Eelco Hoogendoorn