Python 使用NumPy计算-D数组的向量内积
内积是线性代数数学运算中最重要的操作之一,它接受两个向量作为输入并输出一个标量值。它也被称为点积或标量积。两个向量的内积可以表示如下。
a . b = ||a|| ||b|| cos(Ø)
其中,
||a|| 和 ||b||
分别是向量a和b的大小-
Ø
是向量a和b之间的角度 -
a . b
是向量a和b的点积
计算内积
如果我们想要计算数组的内积或点积,它被定义为数组对应元素的乘积之和。让我们以如下形式取两个数组a和b。
a = [a1, a2, a3]
b = [b1, b2, b3]
以下是计算内积的数组的数学表达式。
a . b = a1 * b1 + a2 * b2 + a3 * b3
使用Numpy计算内积
我们可以使用Numpy库中的dot()函数来计算数组的点积。
语法
以下是使用dot()函数计算两个数组元素内积的语法。
np.dot(arr1, arr2)
在这里,
- Numpy 是这个库的名字
-
np 是这个库的别名
-
dot 是用来找到内积的函数
-
arr1 和 arr2 是输入数组
示例
在这个例子中,当我们将两个1维数组作为输入参数传递给dot()函数时,标量积或内积将作为输出返回。
import numpy as np
a = np.array([12,30,45])
b = np.array([23,89,50])
inner_product = np.dot(a,b)
print("The Inner product of the two 1-d arrays:", inner_product)
输出
The Inner product of the two 1-d arrays: 5196
示例
下面是一个使用dot()函数计算1维数组内积的示例。
import numpy as np
a = np.array([34,23,98,79,90,34,23,67])
b = np.array([22,1,95,14,91,5,24,12])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:",inner_product)
输出
The Inner product of the two 2-d arrays: 20903
示例
dot()函数仅接受方阵作为其参数。如果我们尝试传递非方阵的值,将会引发错误。
import numpy as np
a = np.array([[34,23,98,79],[90,34,23,67]])
b = np.array([[22,1,95,14],[91,5,24,12]])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:",inner_product)
错误
Traceback (most recent call last):
File "/home/cg/root/64d07b786d983/main.py", line 4, in <module>
inner_product = np.dot(a,b)
File "<__array_function__ internals>", line 200, in dot
ValueError: shapes (2,4) and (2,4) not aligned: 4 (dim 1) != 2 (dim 0)
示例
在下面的例子中,我们尝试使用dot()函数计算2维数组的内积。
import numpy as np
a = np.array([[34,23],[90,34]])
b = np.array([[22,1],[91,5]])
inner_product = np.dot(a,b)
print("The Inner product of the two 2-d arrays:", inner_product)
输出
The Inner product of the two 2-d arrays: [[2841 149][5074 260]]
示例
现在让我们尝试通过将3D数组作为参数传递给dot()函数来计算向量的内积。
import numpy as np
a = np.array([[[34,23],[90,34]],[[43,23],[10,34]]])
b = np.array([[[22,1],[91,5]],[[22,1],[91,5]]])
inner_product = np.dot(a,b)
print("The Inner product of the two 3-d arrays:", inner_product)
输出
The Inner product of the two 3-d arrays: [[[[2841 149]
[2841 149]]
[[5074 260]
[5074 260]]]
[[[3039 158]
[3039 158]]
[[3314 180]
[3314 180]]]]