I am a newby in broadcasting with numpy. I define three numpy arrays as follows:
from numpy import *
a=array([10,20]).reshape(2,1)
b=array([100,200,300]).reshape(1,3)
c=arange(1,11).reshape(1,1,10)
a+b is a (2,1) vs (1,3) sum so it is supposed to be broadcastable (2vs1 in dim 1, 1vs3 in dim 2, broadcast rule is fulfiled). Indeed it is:
>>> a+b
array([[110, 210, 310],
[120, 220, 320]])
a+c is a (2,1) vs (1,1,10) sum so it is supposed to be broadcastable (2vs1 in dim 1, 1vs1 in dim 2 and 1vs10 in dim 3, broadcast rule is fulfiled). Indeed it is:
>>> a+c
array([[[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]])
b+c is a (1,3) vs (1,1,10) sum so it is supposed to be broadcastable (1vs1 in dim 1, 3vs1 in dim 2, 1vs10 in dim 3. But it seems it is not:
>>> b+c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
The explanation is certainely obvious … but please help me !
returns a (1, 3, 10) array. You have to define the missing axis (the third one).
You can also use
since you imported
* from numpy, which is generally not a good idea.import numpy as npis better. This way you will always know where the methods come from (if you import more packages):