前言
文章主要介绍了 Numpy 中几个乘法函数的使用方法,包含较多的示例代码,建议点击目录直达所需内容,所有的示例代码可以 点击此处 免费获取。
在以下示例代码中,均已事前导入Numpy:import numpy as np
环境
- Windows 10
- Python 3.7.0
- Numpy 1.18.1
np.multiply(x1, x2)
函数注释
该函数是逐元素乘法,如果两个参数x1
和x2
的shape不同,将会进行 broadcastable
Multiply arguments element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays to be multiplied. Ifx1.shape != x2.shape
, they must be broadcastable to a common shape (which becomes the shape of the output).
Returns
-------
y : ndarray
The product ofx1
andx2
, element-wise.
This is a scalar if bothx1
andx2
are scalars.
用法示例
【注】该函数的两个参数的位置可以替换,不影响最后的运算结果。
-
x1
x2
都是 scalar,返回两者的乘积,也是 scalarprint(np.multiply(2, 4)) print(np.multiply(2, 3.8)) ---output--- 8 7.6
-
x1
为 scalar,x2
为 array_like,此时为矩阵与数的乘法,该数与矩阵中每一元素相乘,最后返回同shape的 array。按照文档中的描述,应该是先将scalar 广播(broadcast)为与另一参数同shape的矩阵,再进行逐元素的乘法。print(np.multiply(2, [3, 4, 8])) print(np.multiply(2, np.arange(0, 8).reshape((2, 2, 2)))) ---output--- [ 6 8 16] [[[ 0 2] [ 4 6]] [[ 8 10] [12 14]]]
-
x1
x2
都是 array_like, 如果两个的shape相同,直接逐元素相乘再返回即可,否则需要进行广播(broadcast)。可以广播的最基本的条件就是两者shape的最后一个维度必须是相同的,具体的广播策略比较复杂,通过几个例子来试着理解一下。
【例1】 (2, 2, 3) , (2, 3) —>(2, 2, 3)x1 = np.arange(0, 12).reshape((2, 2, 3)) x2 = np.arange(0, 6).reshape(2, 3) print("-----x1------", x1.shape, "\n", x1) print("-----x2------", x2.shape, "\n", x2) print("-----multiply(x1, x2)------", np.multiply(x1, x2).shape, "\n", np.multiply(x1, x2)) ---output--- -----x1------ (2, 2, 3) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] -----x2------ (2, 3) [[0 1 2] [3 4 5]] -----multiply(x1, x2)------ (2, 2, 3) [[[ 0 1 4] [ 9 16 25]] [[ 0 7 16] [27 40 55]]]
【例2】(2, 2, 1, 3) ,(2, 3) —>(2, 2, 2, 3)
x1 = np.arange(0, 12).reshape((2, 2, 1, 3