nparray变量,如何利用 .dot() 做向量点积和矩阵乘积计算?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文苏南大叔说一个有些烧脑的操作,就是nparray变量乘以nparray变量。换成专业点的名词就是:“向量点积”和“矩阵乘积”。操作方式上有三种方式,分别是:a @ b,np.dot(a,b),a.dot(b)。那么,这些操作有什么区别呢?

苏南大叔的“程序如此灵动”博客,记录苏南大叔和计算机代码的故事。本文测试环境:win10,python@3.12.0。
向量点积
向量点积,实际上就是 一维数组一维数组,两者需要size一致。这个向量点积结果,运算方法是:n1m1 + n2*m2。
下面的代码中,操作的ndarray分别是[1 2 3]和[6 5 4],两者的形状都是一维向量(3,)。计算的结果是这样运算的,1*6 + 2*5 + 3*4 = 6 + 10 + 12 = 28。
import numpy as np
x = np.array([1,2,3]) # [1 2 3]
y = np.arange(6,3,-1) # [6 5 4]
print(x,y) # 形状 需要一致
a1 = x @ y
a2 = y @ x
print(a1,a2) # 28 28
# 1*6 + 2*5 + 3*4 = 6 + 10 + 12 = 28
b1 = np.dot(x,y)
b2 = np.dot(y,x)
print(b1,b2) # 28 28
c1 = x.dot(y)
c2 = y.dot(x)
print(c1,c2) # 28 28过渡一下
这里是一维向量乘以二维矩阵,计算方法类似。但是结果不是一个数字,而是个数组[28]了。并且把x和y互换后,就会报错了。
import numpy as np
x = np.array([1,2,3]) # [1 2 3]
y = np.arange(6,3,-1).reshape((3,1)) # [[6] [5] [4]]
print(x,y)
print(x.shape,y.shape) # 这里的形状并不一致,(3,) (3, 1)。但是属于类似的形状
a1 = x @ y # [28]
# a2 = y @ x # ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 1)
b1 = np.dot(x,y) # [28]
# b2 = np.dot(y,x) # ValueError: shapes (3,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0)
c1 = x.dot(y) # [28]
# c2 = y.dot(x) # ValueError: shapes (3,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0)矩阵乘积
两个二维矩阵乘积,得到的依然是个矩阵。操作的二维数组是:
[ [1, 2], [3, 4], [5, 6] ]
[ [7, 8], [9, 10] ]结果是:
[[ 25 28]
[ 57 64]
[ 89 100]]计算方法是:
7*1 + 9*2 = 258*1 + 10*2 = 287*3 + 9*4 = 21 + 36 = 578*3 + 10*4 = 24 + 40 = 647*5 + 9*6 = 35 + 54 = 898*5 + 10*6 = 40 + 60 = 100
import numpy as np
x = np.array([ [1, 2], [3, 4], [5, 6] ])
y = np.array([ [7, 8], [9, 10] ])
print(x,y)
print(x.shape,y.shape) # 这里的形状并不一致
'''
[[1 2]
[3 4]
[5 6]]
[[ 7 8]
[ 9 10]]
(3, 2) (2, 2)
'''
a1 = x @ y
# a2 = y @ x # ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 3 is different from 2)
b1 = np.dot(x,y)
# b2 = np.dot(y,x) # ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
c1 = x.dot(y)
# c2 = y.dot(x) # ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
'''
[[ 25 28]
[ 57 64]
[ 89 100]]
'''结语
更多苏南大叔的python经验文章,请点击: