Numpy中数组的点乘用函数dot()来实现,而单个*则表示的是数组对应元素的乘法。
一维情况:
In:
a = np.array([1,2,3]) b = np.array([1,2,3]) print(a.dot(b))
Out: 14
一维数组点乘相当于向量乘法,计算结果为一个数(标量),注意要是等长的一维数组才能点乘
二维情况:
In:
a = np.array([[1,2,3], [1,2,3]]) b = np.array([[1,2,3], [1,2,3], [1,2,3]]) print(a.shape) print(b.shape) print(a.dot(b))
Out:
a.shape: (2, 3)
b.shape: (3, 3)
运算结果:
[[ 6 12 18]
[ 6 12 18]]
a.dot(b).shape: (2, 3)
二维数组点乘相当于矩阵的点乘乘法(内积),前一个矩阵a的列数(即二维数组中的第1维,数组维数从0开始)要和第二个矩阵b的行数(二维数组中的第0维)相等。
三维情况:
In:
a = np.array([ [[1,2,3], [1,2,3]] ]) b = np.array([ [[1,2,3], [4,5,6], [7,8,9]], [[1,2,3], [4,5,6], [7,8,9]], ]) print("a.shape: ",a.shape) print("b.shape: ",b.shape) print("运算结果: \n",a.dot(b)) print("a.dot(b).shape: ",a.dot(b).shape)
Out:
a.shape: (1, 2, 3)
b.shape: (2, 3, 3)
运算结果:
[[[[30 36 42]
[30 36 42]]
[[30 36 42]
[30 36 42]]]]
a.dot(b).shape: (1, 2, 2, 3)
三维数组过程比较难理解,简单来说就是前一个数组的最后一维(即数组最内层)的元素个数要等于后一个数组的倒数第二维(上面例子中标红的数字),计算结果的维数格式满足以下规律:
(a数组除最后一维的所有维数(例子中标蓝的部分) , b数组除倒数第二维外的所有维数(例子中标黄的部分))
多维情况(维数>=3)的一些例子:
举例1:
In:
a = np.random.random((1,2,3,4)) #生成一个由0-1的随机数充填,且shape为(1,2,3,4)的4维数组 b = np.random.random((8,5,4,9)) print("a.shape: ",a.shape) print("b.shape: ",b.shape) print("a.dot(b).shape: ",a.dot(b).shape)
Out:
a.shape: (1, 2, 3, 4)
b.shape: (8, 5, 4, 9)
a.dot(b).shape: (1, 2, 3, 8, 5, 9)
举例2:
In:
a = np.random.random((1,2,3,4,2,4,5,6)) #生成一个由0-1的随机数充填,且shape为(1,2,3,4)的4维数组 b = np.random.random((8,5,6,9)) print("a.shape: ",a.shape) print("b.shape: ",b.shape) print("a.dot(b).shape: ",a.dot(b).shape)
Out:
a.shape: (1, 2, 3, 4, 2, 4, 5, 6)
b.shape: (8, 5, 6, 9)
a.dot(b).shape: (1, 2, 3, 4, 2, 4, 5, 8, 5, 9)
总结: 多维数组元素的点乘实际上是对两个数组的最内层元素进行计算。