![](/img/trans.png)
[英]what's the difference between np.linalg.norm(a-x) and np.linalg.norm(a) - np.linalg.norm(x)?
[英]What is the fastest way to apply np.linalg.norm() (python) to each element of a 2d numpy array and a given value?
我想计算给定值 x 和 2d 数组 arr 的每个单元格之间的 L2 范数(当前大小为 1000 x 100。我目前的方法:
for k in range(0, 999):
for l in range(0, 999):
distance = np.linalg.norm([x - arr[k][l]], ord= 2)
x 和 arr[k][l] 都是标量。 我实际上想计算每个数组单元到给定值 x 的成对距离。 最后,对于 1000x 1000 的值,我需要 1000x1000 的距离。 不幸的是,就完成所需的时间而言,上述方法是一个瓶颈。 这就是为什么我正在寻找一种方法来加快速度。 我很感激任何建议。
一个可重现的例子(根据要求):
arr = [[1, 2, 4, 4], [5, 6, 7, 8]]
x = 2
for k in range(0, 3):
for l in range(0, 1):
distance = np.linalg.norm([x - arr[k][l]], ord= 2)
请注意,真正的 arr 要大得多。 这只是一个玩具示例。
实际上,我不一定要使用 np.linalg.norm()。 我只想要给定值 x 的所有这些数组单元的 l2 范数。 如果您知道任何更合适的function,我愿意尝试。
您可以执行以下操作
arr
的子星x
diff = arr - x
distance = np.linalg.norm(diff, axis=2, ord=2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.