Reputation: 482
I'm looking for a bit clarification on broadcasting rules and numpy.dot method over multiplication factor. I have created two arrays of shape (2,) and (3,) which can be multiplied by adding a new axis (3,1 shape) but it couldn't be through np.dot method even though adding a new axis and turning into (3,1) shape. here's the below little test done.
x_1 = np.random.rand(2,)
print(x_1)
x_2 = np.random.rand(3,)
print(x_2)
> [ 0.48362051 0.55892736]
> [ 0.16988562 0.09078386 0.04844093]
x_8 = np.dot(x_1, x_2[:, np.newaxis])
> ValueError: shapes (2,) and (3,1) not aligned: 2 (dim 0) != 3 (dim 0)
x_9 = x_1 * x_2[:, np.newaxis]
print(x_9)
> [[ 0.47231067 0.30899592]
[ 0.17436521 0.11407352]
[ 0.01312074 0.00858387]]
x__7 = x_1[:, np.newaxis] * x_2[:, np.newaxis]
> ValueError: operands could not be broadcast together with shapes (2,1) (3,1)
I understand np.dot of (2,1) & (1,3) works, but why not (2,1) & (3,1) because broadcasting rule number two says, Two dimensions are compatible when one of them is 1. So if one of its dimension is 1, np.dot should work or have I understood rule number two wrong ? Also why X_9 works (multiplication) but not x_8 (np.dot), when both are same shapes.
Upvotes: 0
Views: 1738
Reputation: 1028
np.dot is for matrix-matrix multiplication (where a column vector can be considered to be a matrix with one column and a row vector as a matrix with one row). * (multiplication) is for scalar multiplication in the case that one of the arguments is a scalar, and broadcasting otherwise. So the broadcasting rules are not for np.dot. x_9 works because, as stated in the broadcasting rules here https://docs.scipy.org/doc/numpy-1.12.0/user/basics.broadcasting.html
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when
- they are equal, or
- one of them is 1
so your (only) dimension of x_1, (which is 2) is compatible with the last dimension of x_2 (which is 1 because you added a new dimension), and the remaining dimension is 3.
Upvotes: 1