
2.2 向量乘法:标量乘法、向量内积、逐项积
这一节介绍三种重要的向量乘法:①标量乘法(scalar multiplication);②向量内积(inner product);③逐项积(piecewise product)。
标量乘法
标量乘法运算中,标量乘向量的结果还是向量,相当于缩放。
标量乘法运算规则很简单,向量a乘以k,a的每一个元素均与k相乘,如下例标量2乘行向量[1, 2, 3]

再如,标量乘列向量如

图2.4所示为标量乘法示意图。

图2.4 标量乘法
同理,标量k乘矩阵A的结果是k与矩阵A每一个元素相乘,比如

Bk3_Ch2_06.py完成向量和矩阵标量乘法。
向量内积
向量内积(inner product)的结果为标量。向量内积又叫标量积(scalar product)或点积(dot product)。
向量内积的运算规则是:两个形状相同的向量,对应位置元素一一相乘后再求和。比如,下例计算两个行向量内积

计算两个列向量内积,比如:

图2.5所示为向量内积规则的示意图。

图2.5 向量内积示意图
显然,向量内积满足交换律(commutative),即

向量内积对向量加法满足分配律(distributive over vector addition),即

显然,向量内积不满足结合律(associative),即

Bk3_Ch2_07.py代码用numpy.inner()计算行向量的内积;但是,numpy.inner()函数输入为两个列向量时得到的结果为张量积(tensor product)。
机器学习和深度学习中,张量积是非常重要的向量运算,鸢尾花书将在《矩阵力量》一册中进行详细介绍。
下面举几个例子,让大家管窥标量积的用途。
给定以下五个数字,即

这五个数字求和,可以用标量积计算得到,即

前文提过,[1, 1, 1, 1, 1]T叫作全1向量。
这五个数字的平均值,也可以通过标量积得到,即

计算五个数字的平方和,有

此外,标量积还有重要的几何意义。本书后续将介绍这方面内容。
逐项积
逐项积(piecewise product),也叫阿达玛乘积(hadamard product)。两个相同形状向量的逐项积为对应位置元素分别相乘,结果为相同形状的向量。
逐项积的运算符为⊙。逐项积相当于算术乘法的批量运算。
举个例子,两个行向量逐项积如

图2.6所示为向量逐项积运算示意图。

图2.6 向量逐项积
同理,两个矩阵逐项积的运算前提是——矩阵形状相同。矩阵逐项积运算规则为对应元素相乘,结果形状不变,如

Python中,对于numpy.array()定义的形状相同的向量或矩阵,逐项积可以通过*计算得到。请大家参考Bk3_Ch2_08.py。更多有关NumPy用法,请参考《编程不难》。