轉自https://blog.csdn.net/zenghaitao0128/article/details/78715140
為了區分三種乘法運算的規則,具體分析如下:
import numpy as np
1. np.multiply()函數
函數作用
數組和矩陣對應位置相乘,輸出與相乘數組/矩陣的大小一致
1.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.multiply(A,B) #數組對應元素位置相乘
array([[ 0, 2],
[ 6, 12]])
1.2 矩陣場景
np.multiply(np.mat(A),np.mat(B)) #矩陣對應元素位置相乘,利用np.mat()將數組轉換為矩陣
matrix([[ 0, 2],
[ 6, 12]])
np.sum(np.multiply(np.mat(A),np.mat(B))) #輸出為標量
20
2. np.dot()函數
函數作用
對於秩為1的數組,執行對應位置相乘,然后再相加;
對於秩不為1的二維數組,執行矩陣乘法運算;超過二維的可以參考numpy庫介紹。
2.1 數組場景
2.1.1 數組秩不為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) #對數組執行矩陣相乘運算
array([[ 4, 7],
[ 8, 15]])
2.1.2 數組秩為1的場景
C = np.arange(1,4)
C
array([1, 2, 3])
D = np.arange(0,3)
D
array([0, 1, 2])
np.dot(C,D) #對應位置相乘,再求和
8
2.2 矩陣場景
np.dot(np.mat(A),np.mat(B)) #執行矩陣乘法運算
matrix([[ 4, 7],
[ 8, 15]])
3. 星號(*)乘法運算
作用
對數組執行對應位置相乘
對矩陣執行矩陣乘法運算
3.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]])
A*B #對應位置點乘
array([[ 0, 2],
[ 6, 12]])
3.2矩陣場景
(np.mat(A))*(np.mat(B)) #執行矩陣運算
matrix([[ 4, 7],
[ 8, 15]])
為了區分三種乘法運算的規則,具體分析如下:
import
numpy as np
|
1. np.multiply()函數
函數作用
數組和矩陣對應位置相乘,輸出與相乘數組/矩陣的大小一致
1.1數組場景
【code】
A
=
np.arange(
1
,
5
).reshape(
2
,
2
)
A
|
【result】
array([[
1
,
2
],
[
3
,
4
]])
|
【code】
B
=
np.arange(
0
,
4
).reshape(
2
,
2
)
B
|
【result】
array([[
0
,
1
],
[
2
,
3
]])
|
【code】
np.multiply(A,B)
#數組對應元素位置相乘
|
【result】
array([[
0
,
2
],
[
6
,
12
]])
|
1.2 矩陣場景
【code】
np.multiply(np.mat(A),np.mat(B))
#矩陣對應元素位置相乘,利用np.mat()將數組轉換為矩陣
|
【result】
matrix([[
0
,
2
],
[
6
,
12
]])
|
【code】
np.
sum
(np.multiply(np.mat(A),np.mat(B)))
#輸出為標量
|
【result】
|
2. np.dot()函數
函數作用
對於秩為1的數組,執行對應位置相乘,然后再相加;
對於秩不為1的二維數組,執行矩陣乘法運算;超過二維的可以參考numpy庫介紹。
2.1 數組場景
2.1.1 數組秩不為1的場景
【code】
A
=
np.arange(
1
,
5
).reshape(
2
,
2
)
A
|
【result】
array([[
1
,
2
],
[
3
,
4
]])
|
【code】
B
=
np.arange(
0
,
4
).reshape(
2
,
2
)
B
|
【result】
array([[
0
,
1
],
[
2
,
3
]])
|
【code】
np.dot(A,B)
#對數組執行矩陣相乘運算
|
【result】
array([[
4
,
7
],
[
8
,
15
]])
|
2.1.2 數組秩為1的場景
【code】
C
=
np.arange(
1
,
4
)
C
|
【result】
array([
1
,
2
,
3
])
|
【code】
D
=
np.arange(
0
,
3
)
D
|
【result】
array([
0
,
1
,
2
])
|
【code】
np.dot(C,D)
#對應位置相乘,再求和
|
【result】
8
|
2.2 矩陣場景
【code】
np.dot(np.mat(A),np.mat(B))
#執行矩陣乘法運算
|
【result】
matrix([[
4
,
7
],
[
8
,
15
]])
|
3. 星號(*)乘法運算
作用
對數組執行對應位置相乘
對矩陣執行矩陣乘法運算
3.1 數組場景
【code】
A
=
np.arange(
1
,
5
).reshape(
2
,
2
)
A
|
【result】
array([[
1
,
2
],
[
3
,
4
]])
|
【code】
B
=
np.arange(
0
,
4
).reshape(
2
,
2
)
B
|
【result】
array([[
0
,
1
],
[
2
,
3
]])
|
【code】
A
*
B
#對應位置點乘
|
【result】
array([[
0
,
2
],
[
6
,
12
]])
|
3.2矩陣場景
【code】
(np.mat(A))
*
(np.mat(B))
#執行矩陣運算
|
【result】
matrix([[
4
,
7
],
[
8
,
15
]])
|