dot()函数处理一维数组、二维数组的计算方式。

处理一维数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a = np.arange(5)
b = np.arange(5,10)
c = np.arange(10,14)

print(a, "# a")
print('-'*30)

print(b, "# b")
print('-'*30)

print(c, "# c")
print('-'*30)

print(np.dot(a, b))
print('-'*30)

print(np.dot(a, c))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[0 1 2 3 4] # a
------------------------------
[5 6 7 8 9] # b
------------------------------
[10 11 12 13] # c
------------------------------
80
------------------------------



---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

<ipython-input-58-f134be7edf61> in <module>
15 print('-'*30)
16
---> 17 print(np.dot(a, c))


<__array_function__ internals> in dot(*args, **kwargs)


ValueError: shapes (5,) and (4,) not aligned: 5 (dim 0) != 4 (dim 0)
  • 两个向量必须同维度,否则会报错;
  • 计算过程:$$05+16+27+38+4*9 = 80$$
  • 向量的内积公示:$$a=(x_{1},y_{1}),b=(x_{2},y_{2})$$,内积表示为:$$a*b = x_{1}x_{2}+y_{1}x_{2}$$

处理二维数组

1
2
3
4
5
6
7
8
9
10
11
12
x = np.matrix([[1,2], [3,4]])
print(x, "# x")
print('-'*30)

y = np.matrix("5,6;7,8")
print(y, "# y")
print('-'*30)

print(np.dot(x, y))
print('-'*30)

print(np.dot(y, x))
1
2
3
4
5
6
7
8
9
10
11
[[1 2]
[3 4]] # x
------------------------------
[[5 6]
[7 8]] # y
------------------------------
[[19 22]
[43 50]]
------------------------------
[[23 34]
[31 46]]

image.png
矩阵积计算不遵循交换律,np.dot(a,b) 和 np.dot(b,a) 得到的结果是不一样。