python - numpy matrix multiplication shapes -


this question has answer here:

in matrix multiplication, assume a 3 x 2 matrix (3 rows, 2 columns ) , b 2 x 4 matrix (2 rows, 4 columns ), if matrix c = * b, c should have 3 rows , 4 columns. why numpy not multiplication? when try following code error : valueerror: operands not broadcast shapes (3,2) (2,4)

a = np.ones((3,2)) b = np.ones((2,4)) print a*b 

i try transposing , b , alwasy same answer. why? how do matrix multiplication in case?

the * operator numpy arrays element wise multiplication (similar hadamard product arrays of same dimension), not matrix multiply.

for example:

>>> array([[0],        [1],        [2]]) >>> b array([0, 1, 2]) >>> a*b array([[0, 0, 0],        [0, 1, 2],        [0, 2, 4]]) 

for matrix multiply numpy arrays:

>>> = np.ones((3,2)) >>> b = np.ones((2,4)) >>> np.dot(a,b) array([[ 2.,  2.,  2.,  2.],        [ 2.,  2.,  2.,  2.],        [ 2.,  2.,  2.,  2.]]) 

in addition can use matrix class:

>>> a=np.matrix(np.ones((3,2))) >>> b=np.matrix(np.ones((2,4))) >>> a*b matrix([[ 2.,  2.,  2.,  2.],         [ 2.,  2.,  2.,  2.],         [ 2.,  2.,  2.,  2.]]) 

more information on broadcasting numpy arrays can found here, , more information on matrix class can found here.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -