When multiplication of two similar matrices 1*2
like [1,2]
, [3,5]
is carried out using numpy.dot
, it gives a result, when in fact it should be giving a shape and dimension error like while multiplying two similar arrays. What is going on under the hood?
a=[1,2]
b=[6,3]
result=[np.dot(b, a)]
print(result)
O/P= 12
But,
a=[[1,2]]
b=[[6,3]]
result=[np.dot(b, a)]
print(result)
Error:
O/P= ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)
2 Answers 2
As per the documentation here,
If both
a
andb
are1-D
arrays, it is inner product of vectors (without complex conjugation).If both
a
andb
are2-D
arrays, it is matrix multiplication, but usingmatmul
ora @ b
is preferred.
Case 1: a
and b
are 1-D
arrays, so result is 1*6+2*3=12
.
Case 2: a
and b
are 2-D
arrays, so we will do matrix product of these two. It raises ValueError
since the last dimension of a
is not the same size as the second-to-last dimension of b
.
Adding on to Anubhav Singh's correct answer, note that a matrix product of a row vector with a column vector returns a 1-by-1 matrix whose sole entry is the dot product of the two vectors, so in this case,
In [32]: a = np.array([[1,2]])
In [33]: b = np.array([[6,3]])
In [34]: a @ b.T
Out[34]: array([[12]])
In [35]: np.dot(a, b.T)
Out[35]: array([[12]])
In [36]: np.dot(a[0], b[0])
Out[36]: 12
This is why np.dot
behaves the way it does.
ndarray
, whichdot
will do, they are 1d and 2d respectively.