[英]What is the fastest way to apply np.linalg.norm() (python) to each element of a 2d numpy array and a given value?
I want to compute the L2 norm between a given value x and each cell of a 2d array arr (which is currently of size 1000 x 100. My current approach:我想计算给定值 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 and arr[k][l] are both scalars. x 和 arr[k][l] 都是标量。 I actually want to compute the pairwise distance of each array cell to the given value x.
我实际上想计算每个数组单元到给定值 x 的成对距离。 In the end I need 1000x1000 distances for 1000x 1000 values.
最后,对于 1000x 1000 的值,我需要 1000x1000 的距离。 Unfortunately, the approach above is a bottleneck, when it comes to the time it takes to finish.
不幸的是,就完成所需的时间而言,上述方法是一个瓶颈。 Which is why I am searching for a way to speed this up.
这就是为什么我正在寻找一种方法来加快速度。 I am gratefull for any advice.
我很感激任何建议。
A reproducable example (as asked for):一个可重现的例子(根据要求):
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)
Please note, that the real arr is much bigger.请注意,真正的 arr 要大得多。 This is merely a toy example.
这只是一个玩具示例。
Actually, I am not bound to use np.linalg.norm().实际上,我不一定要使用 np.linalg.norm()。 I simply want the l2 norm for all of these array cells with the given value x.
我只想要给定值 x 的所有这些数组单元的 l2 范数。 If you know any function which is more suitable, I would be willing to try it.
如果您知道任何更合适的function,我愿意尝试。
You can do the followng您可以执行以下操作
x
from the array arr
arr
的子星x
diff = arr - x
distance = np.linalg.norm(diff, axis=2, ord=2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.