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

Stephan Hoyer shoyer at gmail.com
Fri Dec 12 14:28:52 EST 2014


On Fri, Dec 12, 2014 at 5:48 AM, Jaime Fernández del Río <
jaime.frio at gmail.com> wrote:

> np.broadcast is the Python object of the old iterator. It may be a better
> idea to write all of these functions using the new one, np.nditer:
>
> def common_shape(*args):
>     return np.nditer(args).shape[::-1]  # Yes, you do need to reverse it!
>

Unfortunately, that version does not seem to do what I'm looking for:

def common_shape(*args):
    return np.nditer(args).shape[::-1]

x = np.empty((4,))
y = np.empty((2, 3, 4))
print(common_shape(x, y))

Outputs: (6, 4)

And in writing 'broadcast_to', rather than rewriting the broadcasting
> logic, you could check the compatibility of the shape with something like:
>
> np.nditer((arr,), itershape=shape)  # will raise ValueError if shapes
> incompatible
>
> After that, all that would be left is some prepending of zero strides, and
> some zeroing of strides of shape 1 dimensions before calling as_strided
>

Yes, that is a good idea.

Here is a gist with the latest version of this code (shortly to be turned
into a PR):
https://gist.github.com/shoyer/3e36af0a8196c82d4b42
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141212/0910b308/attachment.html>


More information about the NumPy-Discussion mailing list