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

Jaime Fernández del Río jaime.frio at gmail.com
Fri Dec 12 17:34:12 EST 2014


On Fri, Dec 12, 2014 at 11:28 AM, Stephan Hoyer <shoyer at gmail.com> wrote:
>
> 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)
>

Yes, the iterator is a smart beast. I think this is what you need then,
with no reversing involved:

>>> np.nditer((x,y), flags=['multi_index']).shape
(2, 3, 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
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>

-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141212/501f6067/attachment.html>


More information about the NumPy-Discussion mailing list