np.multiply 是如何工作的?

How does np.multiply work?

我正在尝试在 Java 中实现 np.multiply,但我对它的实际作用感到困惑。该文档只是简单地说明它进行逐元素乘法。它与我能找到的任何数学矩阵乘积都不匹配。它部分匹配元素方面的 Hadamard 产品,但不需要相同数量的行和列。有谁知道 np.multiply 的数学乘积是什么,并且有更多关于它是如何工作的信息?

这是我得到的不同输出。这些似乎是非常不同的功能。

a = np.array([[1,1,1],[2,2,2],[2,3]])
b = np.array([[2,3,4]])
print(np.multiply(a,b))
#output
[[1, 1, 1, 1, 1, 1] [2, 2, 2, 2, 2, 2, 2, 2, 2] [2, 3, 2, 3, 2, 3, 2, 3]]]

a = np.array([[1,1,1],[2,2,2]])
b = np.array([[2,3,4]])
print(np.multiply(a,b))
#output
[[2 3 4]
 [4 6 8]]

就像文档中所说的那样,它正在执行逐元素乘法。请注意,在您的第一个示例中,

a = np.array([[1,1,1],[2,2,2],[2,3]])
b = np.array([[2,3,4]])

您有一个对象(列表)数组,因为所有子列表的长度都不相同。

>>> a = np.array([[1,1,1],[2,2,2],[2,3]])
>>> a
array([[1, 1, 1], [2, 2, 2], [2, 3]], dtype=object)

因此,当您将它们相乘时,您就是将一个列表乘以一个整数——结果就是您得到的结果。

例如如果 c = np.multiply(a, b),则:

c[0] == [1, 1, 1] * 2
c[1] == [2, 2, 2] * 3
c[2] == [2, 3] * 4

到目前为止,我们看到相同形状的数组相乘产生 Handamard product. What about when they aren't the same shape? In the case, numpy tries to "broadcast" them to the same shape. The rules can be somewhat complex, so I won't try to reproduce them here, but they can be found at http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html。标量数组乘法与标量矩阵乘法在数学中的工作原理相同。对于形状不同的数组,尾随维度必须匹配,维度较少的数组将根据需要重复多次以填充缺失的维度,然后执行 Handamard 乘积。

例如

a = np.array([[1, 2, 3], [1, 2, 3]])
b = np.array([3, 2, 1])
c = np.array([[3, 2, 1], [3, 2, 1]])

在这种情况下,a * ba * c 将给出相同的结果。


显然,我描述它的方式不是它的实现方式(那将是非常低效的),但它有助于思考它。