[Numpy-discussion] Add a function to broadcast arrays to a given shape to numpy's stride_tricks?

Matthew Brett matthew.brett at gmail.com
Thu Dec 11 12:38:16 EST 2014


On Sunday, December 7, 2014, Stephan Hoyer <shoyer at gmail.com> wrote:

> I recently wrote function to manually broadcast an ndarray to a given
> shape according to numpy's broadcasting rules (using strides):
>
> https://github.com/xray/xray/commit/7aee4a3ed2dfd3b9aff7f3c5c6c68d51df2e3ff3
>
> The same functionality can be done pretty straightforwardly with
> np.broadcast_arrays, but that function does both too much (I don't actually
> have a second array that needs to be broadcast) and not enough (I need to
> create a dummy array to broadcast against it).
>
> This approach is simpler, and also, according to my benchmarks, about 3x
> faster than np.broadcast_arrays:
>
> In [1]: import xray
> In [2]: import numpy as np
> In [3]: x = np.random.randn(4)
> In [4]: y = np.empty((2, 3, 4))
> In [5]: %timeit xray.core.utils.as_shape(x, y.shape)
> 100000 loops, best of 3: 17 µs per loop
> In [6]: %timeit np.broadcast_arrays(x, y)[0]
> 10000 loops, best of 3: 47.4 µs per loop
>
> Would this be a welcome addition to numpy's lib.stride_tricks? If so, I
> will put together a PR.
>
> In my search, I turned up a Stack Overflow post looking for similar
> functionality:
>
> https://stackoverflow.com/questions/11622692/is-there-a-better-way-to-broadcast-arrays
>

That would be excellent - I ran into exactly the same problem, with the
same conclusions, but I was lazier than you were and I did write a routine
for making a dummy array in order to use broadcast_arrays:

https://github.com/nipy/nibabel/blob/master/nibabel/fileslice.py#L722
https://github.com/nipy/nibabel/blob/master/nibabel/parrec.py#L577

Having a function to do this would be much clearer, thanks for doing that.

Cheers,

Matthew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141211/e1e2fe95/attachment.html>


More information about the NumPy-Discussion mailing list