shape (3,) is treated as (1,3)
shape column sizes must match in order to broadcast
any ufunc can be broadcasted, not just +-
import numpy as np
a = np.arange(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a +10
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
a = np.arange(15).reshape(3,5)
a + 1000
array([[1000, 1001, 1002, 1003, 1004], [1005, 1006, 1007, 1008, 1009], [1010, 1011, 1012, 1013, 1014]])
a = np.arange(3)
a
array([0, 1, 2])
b = np.eye(3)
b
array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
a + b
array([[1., 1., 2.], [0., 2., 2.], [0., 1., 3.]])
b = np.ones((2,3), int)
a + b
array([[1, 2, 3], [1, 2, 3]])
b = np.arange(10)
b
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a + b
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-12-bd58363a63fc> in <module> ----> 1 a + b ValueError: operands could not be broadcast together with shapes (3,) (10,)
# even though 6 is divisable by 3, a refuses to be shared :(
b = np.arange(6)
a + b
# as soon as we reshape b to have the same column size as a, it works.
a + b.reshape(2,3)
a = np.arange(3)
a.shape
a
b = np.arange(3)[:, np.newaxis]
b.shape
b
# it is working because b has 1 column
a + b
X = np.ones((2,1), dtype=int)
X
Y = np.ones((1,2), dtype=int)
Y
X - Y
X = np.full((2,1),2)
X
Y = np.full((1,2),1)
Y
X - Y
X = np. array([[1],[2]])
X
Y = np.array([[2, 1]])
Y
X -Y
If we think of each row is a point on 2-D space (like a sheet of paper), if we want to get its distance from all other points, including itself,which we called X here,
then we reshape a copy of it into 3-D space, which we call Y. So when we take the difference between them, X will be duplicated along the 3rd dimension.
The trick is that we do not reshape Y in (2,2,1). Rather, we reshape Y in (2,1,2).
In the first 2D space, X is (2,2) whereas Y is (2,1). So Y has to duplicate itself to become (2,2).
In the last dimension, X has to duplicate itself for Y.
X = np.array([[1,0],
[2,1]])
X
Y = X.reshape(2,1,2)
Y
#[[0,0] ,[-1,-1]] = [[1, 0]] - [[1, 0],[2, 1]]
#[[ 1, 1],[ 0, 0]]] = [[2, 1]] - [[1, 0],[2, 1]]
Y-X
np.array([[1, 0]]) - np.array([[1, 0],[2, 1]])
np.array([[2, 1]]) - np.array([[1, 0],[2, 1]])
np.hstack((np.array([[1, 0]]) - np.array([[1, 0],[2, 1]]), np.array([[2, 1]])) - np.array([[1, 0],[2, 1]]) )