I have a numpy matrix b = np.array([[1,0,1,0],[0,0,0,1]])
and I want to product it element-wise into a 3-dim array a = np.array([[[1,2,3,4], [5,6,7,8], [9,10,11,12]], [[13,14,15,16], [17,18,19,20], [21,22,23,24]]])
for each index on the second dimension. So, the result I expect should be as follows:
[[[1,0,3,0], [5,0,7,0], [9,0,11,0]], [[0,0,0,16], [0,0,0,20], [0,0,0,24]]]
Numpy does not broadcast if I do a * b
. I was thinking of broadcasting b in its second dimension. I tried np.broadcast_to(b, (2,3,4))
but I got error. I tried (np.broadcast_to(b, (3,2,4)).reshape(2,3,4))
but the output is not as expected.
You need to reshape:
c = b.reshape(2,-1,4)*a
Use None/newaxis
to added a new middle dimension ( reshape
also does this):
In [36]: b.shape
Out[36]: (2, 4)
In [37]: a.shape
Out[37]: (2, 3, 4)
In [38]: b[:,None,:]*a
Out[38]:
array([[[ 1, 0, 3, 0],
[ 5, 0, 7, 0],
[ 9, 0, 11, 0]],
[[ 0, 0, 0, 16],
[ 0, 0, 0, 20],
[ 0, 0, 0, 24]]])
In [39]: b[:,None,:].shape
Out[39]: (2, 1, 4)
broadcast_to
can't add that extra dimension automatically. It follows the same rules as b*a
operations. It can add leading dimensions if needed, and scale size 1 dimensions. But for anything else, you have to be explicit.
In [41]: np.broadcast_to(b, (2,3,4))
Traceback (most recent call last):
File "<ipython-input-41-3c3268de7ce1>", line 1, in <module>
np.broadcast_to(b, (2,3,4))
File "<__array_function__ internals>", line 5, in broadcast_to
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/stride_tricks.py", line 411, in broadcast_to
return _broadcast_to(array, shape, subok=subok, readonly=True)
File "/usr/local/lib/python3.8/dist-packages/numpy/lib/stride_tricks.py", line 348, in _broadcast_to
it = np.nditer(
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,4) and requested shape (2,3,4)
In [42]: np.broadcast_to(b[:,None,:], (2,3,4))
Out[42]:
array([[[1, 0, 1, 0],
[1, 0, 1, 0],
[1, 0, 1, 0]],
[[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.