简体   繁体   中英

numpy Matrix Multiplication n x m * m x p = n x p

I am trying to multiply two numpy arrays as matrices. I expect that if A is an nxm matrix and B is an mxp matrix, then A*B yields an nxp matrix.

This code creates a 5x3 matrix and a 3x1 matrix, as verified by the shape property. I was careful to create both arrays in two dimensions. The final line performs the multiplication, and I expect a 5x1 matrix.

A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
print(A)
print(A.shape)
B = np.array([[2],[3],[4]])
print(B)
print(B.shape)
print(A*B)

Result

[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]
 [5 5 5]]
(5, 3)
[[2]
 [3]
 [4]]
(3, 1)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-38-653ff6c66fb7> in <module>()
      5 print(B)
      6 print(B.shape)
----> 7 print(A*B)

ValueError: operands could not be broadcast together with shapes (5,3) (3,1) 

Even the exception message indicates that the inner dimensions (3 and 3) match. Why did multiplication throw an exception? How should I generate a 5x1 matrix?

I am using Python 3.6.2 and Jupyter Notebook server 5.2.2.

The * operator provides elementwise multiplication, which requires that the arrays are the same shape, or are 'broadcastable' .

For the dot product, use A.dot(B) or in many cases you can use A @ B (in Python 3.5; read how it differs from dot .

>>> import numpy as np
>>> A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
>>> B = np.array([[2],[3],[4]])
>>> A @ B
array([[ 9],
       [18],
       [27],
       [36],
       [45]])

For even more options, especially for handling higher dimensional arrays, there's also np.matmul .

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