这里是原始输入变量:
A = np.array([[1,1,1,1],[2,2,2,2]])
B = np.array([[1,2,3,4],[1,1,1,1],[1,2,1,9]])
A
# array([[1, 1, 1, 1],
# [2, 2, 2, 2]])
B
# array([[1, 2, 3, 4],
# [1, 1, 1, 1],
# [1, 2, 1, 9]])
A 是一个 2x4 数组。
B 是一个 3x4 数组。
我们希望在一个完全向量化的操作中计算欧几里得距离矩阵操作,其中dist[i,j] 包含 A 中的第 i 个实例与 B 中的第 j 个实例之间的距离。因此,dist 在此示例中为 2x3。
距离
表面上可以用 numpy as 编写
dist = np.sqrt(np.sum(np.square(A-B))) # DOES NOT WORK
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ValueError: operands could not be broadcast together with shapes (2,4) (3,4)
但是,如上所示,问题在于逐元素减法运算A-B 涉及不兼容的数组大小,特别是第一维中的 2 和 3。
A has dimensions 2 x 4
B has dimensions 3 x 4
为了进行元素减法,我们必须填充 A 或 B 以满足 numpy 的广播规则。我将选择用一个额外的维度填充 A,使其变为 2 x 1 x 4,这允许数组的维度排列以进行广播。有关 numpy 广播的更多信息,请参阅 tutorial in the scipy manual 和 this tutorial 中的最后一个示例。
您可以使用np.newaxis 值或np.reshape 命令执行填充。我在下面显示:
# First approach is to add the extra dimension to A with np.newaxis
A[:,np.newaxis,:] has dimensions 2 x 1 x 4
B has dimensions 3 x 4
# Second approach is to reshape A with np.reshape
np.reshape(A, (2,1,4)) has dimensions 2 x 1 x 4
B has dimensions 3 x 4
如您所见,使用任何一种方法都可以使尺寸对齐。我将使用np.newaxis 的第一种方法。所以现在,这将创建 A-B,它是一个 2x3x4 数组:
diff = A[:,np.newaxis,:] - B
# Alternative approach:
# diff = np.reshape(A, (2,1,4)) - B
diff.shape
# (2, 3, 4)
现在我们可以将差分表达式放入dist方程语句中得到最终结果:
dist = np.sqrt(np.sum(np.square(A[:,np.newaxis,:] - B), axis=2))
dist
# array([[ 3.74165739, 0. , 8.06225775],
# [ 2.44948974, 2. , 7.14142843]])
请注意,sum 超过 axis=2,这意味着在 2x3x4 数组的第三个轴上求和(其中轴 id 以 0 开头)。
如果你的数组很小,那么上面的命令就可以正常工作。但是,如果您有大型数组,那么您可能会遇到内存问题。请注意,在上面的示例中,numpy 在内部创建了一个 2x3x4 数组来执行广播。如果我们将 A 的维度推广为 a x z 并将 B 的维度推广为 b x z,那么 numpy 将在内部创建一个 a x b x z 数组用于广播。
我们可以通过做一些数学运算来避免创建这个中间数组。因为您将欧几里得距离计算为差平方和,所以我们可以利用差平方和可以重写的数学事实。
请注意,中间项涉及 element-wise 乘法的总和。这个乘法之和被称为点积。因为 A 和 B 都是一个矩阵,那么这个运算实际上就是一个矩阵乘法。因此,我们可以将上面的内容重写为:
然后我们可以编写以下 numpy 代码:
threeSums = np.sum(np.square(A)[:,np.newaxis,:], axis=2) - 2 * A.dot(B.T) + np.sum(np.square(B), axis=1)
dist = np.sqrt(threeSums)
dist
# array([[ 3.74165739, 0. , 8.06225775],
# [ 2.44948974, 2. , 7.14142843]])
请注意,上面的答案与之前的实现完全相同。同样,这里的优点是我们不需要为广播创建中间的 2x3x4 数组。
为了完整起见,让我们再次检查threeSums 中每个加法的维度是否允许广播。
np.sum(np.square(A)[:,np.newaxis,:], axis=2) has dimensions 2 x 1
2 * A.dot(B.T) has dimensions 2 x 3
np.sum(np.square(B), axis=1) has dimensions 1 x 3
因此,正如预期的那样,最终的 dist 数组的尺寸为 2x3。
this tutorial 中也讨论了这种使用点积代替逐元素乘法之和的方法。