简体   繁体   中英

numpy.dot(a, b) gives wrong result on multiplication of matrices with similar dimenstions

Let matrices a, b be [ 1, 2, 3, 4 ] ie of (1 x 4) dimension.
On applying numpy.dot(a, b) the result is 30 instead of raising exception that both the matrices shapes are not aligned.
How can a (mxn) matrix be multiplied with (mxn) matrix? Does numpy automatically transposes one matrix to align their shapes and then multiply?

In [59]: a = b = np.matrix([1,2,3,4])

In [60]: np.dot(a.T, b)      # 1
Out[60]: 
matrix([[ 1,  2,  3,  4],
        [ 2,  4,  6,  8],
        [ 3,  6,  9, 12],
        [ 4,  8, 12, 16]])

In [63]: np.dot(a, b.T)      # 2
Out[63]: matrix([[30]])

In [64]: np.dot(a, b)        # 3
ValueError: shapes (1,4) and (1,4) not aligned: 4 (dim 1) != 1 (dim 0)

More generally, if X has shape (m, n) and Y has shape (n, p) , then np.dot(X,Y) returns an array of shape (m, p) and which is the result of matrix multiplication.

  1. Since aT has shape (4, 1) , and b has shape (1, 4) , the result of matrix multiplication is an array of shape (4, 4) .

  2. Since a has shape (1, 4) , and bT has shape (4, 1) , the result of matrix multiplication is an array of shape (1, 1) .

  3. np.dot(a, b) raises a ValueError since arrays of shape (1, 4) and (1, 4) can not be matrix multiplied. NumPy never transposes axes automatically.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM