Several Matrix Multiplications in Python (Summary)

  • 2021-07-13 05:40:45
  • OfStack

1. np.dot()

1. Definition of matrix multiplication in homolinear algebra. np. dot (A, B) says:

For two-dimensional matrices, calculate the matrix product in the true sense. For a 1-dimensional matrix, calculate the inner product of the two.

2. Code

"code"


import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
# 2-D array: 3 x 2
two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])

two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
print('two_multi_res: %s' %(two_multi_res))

# 1-D array
one_dim_vec_one = np.array([1, 2, 3])
one_dim_vec_two = np.array([4, 5, 6])
one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
print('one_result_res: %s' %(one_result_res))

"result"

two_multi_res: [[22 28]
[49 64]]
one_result_res: 32

2. np. multiply () or *

1. In Python, there are two ways to multiply corresponding elements (element-wise product).

One is np. multiply () The other one is *

2. Code

"code"


import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])

#  Multiplication of corresponding elements  element-wise product
element_wise = two_dim_matrix_one * another_two_dim_matrix_one
print('element wise product: %s' %(element_wise))

#  Multiplication of corresponding elements  element-wise product
element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
print('element wise product: %s' % (element_wise_2))

"result"

element wise product: [[ 7 16 27]
[16 35 6]]
element wise product: [[ 7 16 27]
[16 35 6]]


Related articles: