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.
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.
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.])
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.
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.
how about use transpose:
(a.T + c.T).T
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.
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