Detailed explanation of the difference between np. multiply of np. dot of and asterisk of * in python

  • 2021-10-13 08:13:24
  • OfStack

Directory 1. np. multiply () Function
1.1 Array Scenarios
1.2 Matrix Scenario
2. np. dot () Function
2.1 Array Scenarios
2.2 Matrix Scenarios
3. Asterisk (*) multiplication
3.1 Array Scenarios
3.2 Matrix Scenario

In order to distinguish the three multiplication rules, the specific analysis is as follows:


import numpy as np

1. np. multiply () Function

Functional action

The corresponding position of array and matrix is multiplied, and the output is 1 to the size of the multiplied array/matrix

1.1 Array Scenarios


A = np.arange(1,5).reshape(2,2)
A

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


B = np.arange(0,4).reshape(2,2)
B

array([[0, 1],
[2, 3]])


np.multiply(A,B)  # Array corresponding element position multiplication 

array([[ 0, 2],
[ 6, 12]])

1.2 Matrix Scenario


np.multiply(np.mat(A),np.mat(B))  # Matrix corresponding element position multiplication, using np.mat() Convert an array to a matrix 

matrix([[ 0, 2],
[ 6, 12]])


np.sum(np.multiply(np.mat(A),np.mat(B))) # Output is scalar 

20

2. np. dot () Function

Functional action

For arrays with rank 1, multiply the corresponding positions and then add them;

For 2-dimensional arrays with rank not 1, perform matrix multiplication; For more than 2 dimensions, please refer to numpy library.

2.1 Array Scenarios

2.1. 1 Scenarios with Array Rank Not 1


A = np.arange(1,5).reshape(2,2)
A

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


B = np.arange(0,4).reshape(2,2)
B

array([[0, 1],
[2, 3]])


np.dot(A,B) # Perform matrix multiplication on arrays 

array([[ 4, 7],
[ 8, 15]])

2.1. 2 Scenarios with Array Rank 1


C = np.arange(1,4)
C

array([1, 2, 3])


A = np.arange(1,5).reshape(2,2)
A
0

array([0, 1, 2])


A = np.arange(1,5).reshape(2,2)
A
1

8

2.2 Matrix Scenarios


A = np.arange(1,5).reshape(2,2)
A
2

matrix([[ 4, 7],
[ 8, 15]])

3. Asterisk (*) multiplication

Action

Multiplying arrays by corresponding positions

Perform matrix multiplication on a matrix

3.1 Array Scenarios


A = np.arange(1,5).reshape(2,2)
A

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


A = np.arange(1,5).reshape(2,2)
A
4

array([[0, 1],
[2, 3]])


A = np.arange(1,5).reshape(2,2)
A
5

array([[ 0, 2],
[ 6, 12]])

3.2 Matrix Scenario


A = np.arange(1,5).reshape(2,2)
A
6

matrix([[ 4, 7],
[ 8, 15]])


Related articles: