Why does numpy.broadcast "transpose" the results of vstack and similar functions?

Note:

In [1]: import numpy as np In [2]: x = np.array([1, 2, 3]) In [3]: np.vstack([x, x]) Out[3]: array([[1, 2, 3], [1, 2, 3]]) In [4]: np.vstack(np.broadcast(x, x)) Out[4]: array([[1, 1], [2, 2], [3, 3]]) 

Similarly for column_stack and row_stack ( hstack behaves differently in this case, but also different when used with broadcast). Why?

Iโ€™m after the logic, but I donโ€™t find a way to โ€œrestoreโ€ this behavior (I'm just fine with it, it's just not intuitive).

+5
source share
1 answer

np.broadcast returns an instance of an iterator object that describes how arrays should be translated together. 1 Among other things, it describes the shape and number of dimensions that the resulting array will have,

Actually, when you actually iterate over this object in Python, you return tuples of elements from each input array:

 >>> b = np.broadcast(x, x) >>> b.shape (3,) >>> b.ndim 1 >>> list(b) [(1, 1), (2, 2), (3, 3)] 

This tells us that if we were to perform the actual operation on arrays (for example, x+x ), NumPy would return an array of the form (3,) , one dimension and combine the elements in the tuple to create values โ€‹โ€‹in the final array (for example, it would perform 1+1 , 2+2 , 3+3 to add).

If you delve into the vstack source, you will find that everything it does is make sure that the elements of iterability are at least two-dimensional, and then stack them along the 0 axis.

In the case of b = np.broadcast(x, x) this means that we collect the following arrays:

 >>> [np.atleast_2d(_m) for _m in b] [array([[1, 1]]), array([[2, 2]]), array([[3, 3]])] 

These three small arrays are then stacked vertically, producing the output you mark.


1 Exactly how arrays of different dimensions are repeated in parallel lies at the heart of how NumPy broadcasting works. The code can be found mainly in iterators.c . An interesting review of the multidimensional NumPy iterator, written by Travis Oliphant himself, can be found in the book Beautiful Code .

+5
source

Source: https://habr.com/ru/post/1245876/


All Articles