使用NumPy获取多维矢量点积
给定两个多维矢量,任务是编写一个Python程序,使用NumPy得到两个多维矢量的点积。
例子:让我们取2个向量a = [2,5,3]和b = [6,3,1] 。
点积(ab) = (a[0] * b[0])+ (a[1] * b[1]) + (a[2] * b[2]) = (26)+ (53) + (3*1) = 30
点积是指在向量的每个位置上的元素的乘积之和。
一维矢量的点积。
现在让我们在python中实现这一点。但是我们不需要从头开始编码,这要感谢Numpy。Numpy模块有一个方法dot,它接收两个向量并返回它们的点积
# import numpy
import numpy as np
# initialize vectors
a = np.array([2,5,3])
b = np.array([6,3,1])
# calculating Dot product form np.dot
c = np.dot(a,b)
print("Dot product of a and b is: ",c)
输出:
Dot product of a and b is: 30
二维向量的点积。
二维向量的点积是简单的矩阵乘法。在一维向量中,每个向量的长度应该是相同的,但当涉及到二维向量时,我们将有两个方向的长度即行和列。二维向量的行和列不一定相同,但第一个向量的列数应与第二个向量的行数一致。
示例:
让我们用Python(Numpy模块)做同样的事情
# import numpy
import numpy as np
# initialize 2d vectors
a = np.array([[3, 9],
[2, 5]])
b = np.array([[6, 1],
[4, 8]])
# Checking the condition "No. of columns
# of first vector == No. of rows of the
# second vector"
if a.shape[1] == b.shape[0]:
# calculating Dot product using np.dot
c = np.dot(a, b)
print("Dot product of a and b is:\n", c)
else:
print("No. of columns of first vector should match\
with No. of rows of the second vector")
输出:
Dot product of a and b is:
[[54 75]
[32 42]]
示例:
在这个例子中,采用与上例相同的方法,我们要处理不同的数据点,并添加一个if语句,以防代码产生错误。
# import numpy
import numpy as np
# initialize vectors
a = np.array([[3,9,6],
[2,5,2]])
b = np.array([[6,1],
[4,8],
[7,5]])
# Checking the condition "No. of columns
# of first vector == No. of rows of the
# second vector"
if a.shape[1] == b.shape[0]:
# calculating Dot product using np.dot
c = np.dot(a,b)
print("Dot product of a and b is:\n",c)
else:
print("No. of columns of first vector should match with \
No. of rows of the second vector")
输出:
Dot product of a and b is:
[[ 96 105]
[ 46 52]]
如果条件不满足,它将抛出一个错误,让我们删除我们的if块并计算不同形状的点积,看看什么是错误。
# import numpy
import numpy as np
# initialize vectors
a = np.array([[3,9],
[2,5]])
b = np.array([[6,1],
[4,8],
[7,5]])
print("Shape of vector a: ",a.shape)
print("Shape of vector b: ",b.shape)
# calculating Dot product using np.dot
c = np.dot(a,b)
print("Dot product of a and b is:\n",c)
Shape of vector a: (2, 2)
Shape of vector b: (3, 2)
—————————————————————————
ValueError Traceback (most recent call last)
in 12
13 # calculating Dot product using np.dot
—> 14 c = np.dot(a,b)
15 print(“Dot product of a and b is:\n”,c)
<__array_function__ internals> in dot(*args, **kwargs)
ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)