【问题标题】:How can the Euclidean distance be calculated with NumPy?如何用 NumPy 计算欧几里得距离?
【发布时间】:2010-11-26 23:12:19
【问题描述】:

我在 3D 中有两个点:

(xa, ya, za)
(xb, yb, zb)

我要计算距离:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

使用 NumPy 或一般的 Python 执行此操作的最佳方法是什么?我有:

import numpy
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))

【问题讨论】:

  • 要清楚,您的 3D 坐标点实际上是 1D 数组 ;-)

标签: python numpy euclidean-distance


【解决方案1】:

对于有兴趣同时计算多个距离的人,我使用perfplot(我的一个小项目)做了一个小比较。

第一个建议是组织您的数据,使数组具有维度 (3, n)(并且显然是 C 连续的)。如果添加发生在连续的第一维中,事情会更快,如果您将sqrt-sumaxis=0 一起使用,linalg.normaxis=0 一起使用,或者

a_min_b = a - b
numpy.sqrt(numpy.einsum('ij,ij->j', a_min_b, a_min_b))

这是最快的变体。 (这实际上只适用于一行。)

您在第二个轴上总结的变体axis=1 都慢得多。


重现情节的代码:

import numpy
import perfplot
from scipy.spatial import distance


def linalg_norm(data):
    a, b = data[0]
    return numpy.linalg.norm(a - b, axis=1)


def linalg_norm_T(data):
    a, b = data[1]
    return numpy.linalg.norm(a - b, axis=0)


def sqrt_sum(data):
    a, b = data[0]
    return numpy.sqrt(numpy.sum((a - b) ** 2, axis=1))


def sqrt_sum_T(data):
    a, b = data[1]
    return numpy.sqrt(numpy.sum((a - b) ** 2, axis=0))


def scipy_distance(data):
    a, b = data[0]
    return list(map(distance.euclidean, a, b))


def sqrt_einsum(data):
    a, b = data[0]
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum("ij,ij->i", a_min_b, a_min_b))


def sqrt_einsum_T(data):
    a, b = data[1]
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum("ij,ij->j", a_min_b, a_min_b))


def setup(n):
    a = numpy.random.rand(n, 3)
    b = numpy.random.rand(n, 3)
    out0 = numpy.array([a, b])
    out1 = numpy.array([a.T, b.T])
    return out0, out1


b = perfplot.bench(
    setup=setup,
    n_range=[2 ** k for k in range(22)],
    kernels=[
        linalg_norm,
        linalg_norm_T,
        scipy_distance,
        sqrt_sum,
        sqrt_sum_T,
        sqrt_einsum,
        sqrt_einsum_T,
    ],
    xlabel="len(x), len(y)",
)
b.save("norm.png")

【讨论】:

  • 谢谢。我今天学到了新东西!对于一维数组,字符串为i,i->
  • 如果有内存消耗的比较,那就更酷了
  • 我想使用您的代码,但我很难理解数据的组织方式。能给我举个例子吗? data 的外观如何?
  • 非常简洁的项目和发现。我一直在做一些相同性质的半成品图,所以我想我会切换到你的项目并贡献差异,如果你喜欢它们。
  • @JohannesWiesner 父母说形状必须是(3,n)。我们可以打开一个 python 终端,看看它是什么样子的。 >>> np.zeros((3, 1)) array([[0.], [0.], [0.]]) 或 5 个值:>>> np.zeros((3, 5))数组([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]])
【解决方案2】:

使用 NumPy 或一般的 Python 执行此操作的最佳方法是什么?我有:

最好的方法是最安全也是最快的

我建议使用hypot以获得可靠的结果,因为与编写自己的sqroot计算器相比,下溢和溢出的机会非常小

让我们看看 math.hypot、np.hypot 与 vanilla np.sqrt(np.sum((np.array([i, j, k])) ** 2, axis=1))

i, j, k = 1e+200, 1e+200, 1e+200
math.hypot(i, j, k)
# 1.7320508075688773e+200
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# RuntimeWarning: overflow encountered in square

Speed wise math.hypot 看起来更好

%%timeit
math.hypot(i, j, k)
# 100 ns ± 1.05 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%%timeit
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# 6.41 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

下溢

i, j = 1e-200, 1e-200
np.sqrt(i**2+j**2)
# 0.0

溢出

i, j = 1e+200, 1e+200
np.sqrt(i**2+j**2)
# inf

没有下溢

i, j = 1e-200, 1e-200
np.hypot(i, j)
# 1.414213562373095e-200

无溢出

i, j = 1e+200, 1e+200
np.hypot(i, j)
# 1.414213562373095e+200

Refer

【讨论】:

    【解决方案3】:

    其他答案适用于浮点数,但不能正确计算容易上溢和下溢的整数 dtype 的距离。请注意,即使scipy.distance.euclidean 也有这个问题:

    >>> a1 = np.array([1], dtype='uint8')
    >>> a2 = np.array([2], dtype='uint8')
    >>> a1 - a2
    array([255], dtype=uint8)
    >>> np.linalg.norm(a1 - a2)
    255.0
    >>> from scipy.spatial import distance
    >>> distance.euclidean(a1, a2)
    255.0
    

    这很常见,因为许多图像库将图像表示为 dtype="uint8" 的 ndarray。这意味着如果你有一个由非常深的灰色像素组成的灰度图像(比如所有像素都有颜色#000001)并且你将它与黑色图像(#000000)进行比较,你最终可以得到x-y由所有单元格中的255 组成,这表明两个图像彼此相距很远。对于无符号整数类型(例如 uint8),您可以安全地计算 numpy 中的距离:

    np.linalg.norm(np.maximum(x, y) - np.minimum(x, y))
    

    对于有符号整数类型,可以先转换为浮点数:

    np.linalg.norm(x.astype("float") - y.astype("float"))
    

    具体图片数据,可以使用opencv的norm方法:

    import cv2
    cv2.norm(x, y, cv2.NORM_L2)
    

    【讨论】:

      【解决方案4】:

      您可以只减去向量,然后减去内积。

      按照你的例子,

      a = numpy.array((xa, ya, za))
      b = numpy.array((xb, yb, zb))
      
      tmp = a - b
      sum_squared = numpy.dot(tmp.T, tmp)
      result = numpy.sqrt(sum_squared)
      

      【讨论】:

      • 这会给我距离的平方。你在这里少了一个 sqrt。
      【解决方案5】:

      使用numpy.linalg.norm:

      dist = numpy.linalg.norm(a-b)
      

      你可以在Introduction to Data Mining找到这背后的理论

      之所以有效,是因为欧几里得距离l2范数numpy.linalg.normord参数的默认值为2。

      【讨论】:

      【解决方案6】:

      一个不错的单线:

      dist = numpy.linalg.norm(a-b)
      

      但是,如果速度是一个问题,我建议您在您的机器上进行试验。我发现在我的机器上使用math 库的sqrt** 运算符比单线NumPy 解决方案快得多。

      我使用这个简单的程序运行了我的测试:

      #!/usr/bin/python
      import math
      import numpy
      from random import uniform
      
      def fastest_calc_dist(p1,p2):
          return math.sqrt((p2[0] - p1[0]) ** 2 +
                           (p2[1] - p1[1]) ** 2 +
                           (p2[2] - p1[2]) ** 2)
      
      def math_calc_dist(p1,p2):
          return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
                           math.pow((p2[1] - p1[1]), 2) +
                           math.pow((p2[2] - p1[2]), 2))
      
      def numpy_calc_dist(p1,p2):
          return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))
      
      TOTAL_LOCATIONS = 1000
      
      p1 = dict()
      p2 = dict()
      for i in range(0, TOTAL_LOCATIONS):
          p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
          p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
      
      total_dist = 0
      for i in range(0, TOTAL_LOCATIONS):
          for j in range(0, TOTAL_LOCATIONS):
              dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
              total_dist += dist
      
      print total_dist
      

      在我的机器上,math_calc_dist 的运行速度比 numpy_calc_dist 快得多:1.5 秒对 23.5 秒。

      为了在fastest_calc_distmath_calc_dist 之间获得可测量的差异,我必须将TOTAL_LOCATIONS 提高到6000。然后fastest_calc_dist 需要大约50 秒,而math_calc_dist 需要大约60 秒。

      您也可以尝试使用numpy.sqrtnumpy.square,尽管它们都比我机器上的math 替代品慢。

      我的测试是使用 Python 2.6.6 运行的。

      【讨论】:

      • 你严重误解了如何使用 numpy...不要使用循环或列表推导。如果您正在迭代并将该函数应用于 each 项,那么,是的,numpy 函数会更慢。重点是对事物进行矢量化。
      • 如果我将 numpy.array 调用移动到创建点的循环中,我确实会使用 numpy_calc_dist 获得更好的结果,但它仍然比 fast_calc_dist 慢 10 倍。如果我有那么多点并且我需要找到每对之间的距离,我不确定我还能做些什么来利用 numpy。
      • 我意识到这个帖子很旧,但我只是想加强 Joe 所说的话。您没有正确使用 numpy。您正在计算的是从 p1 中的每个点到 p2 中的每个点的距离之和。使用 numpy/scipy 的解决方案在我的机器上要快 70 倍以上。将 p1 和 p2 放入一个数组中(如果将它们定义为字典,即使使用循环)。然后你可以一步得到总和,scipy.spatial.distance.cdist(p1, p2).sum()。就是这样。
      • 或者使用numpy.linalg.norm(p1-p2).sum()得到p1中的每个点和p2中的对应点之间的总和(即不是p1中的每个点到p2中的每个点)。而且,如果您确实希望 p1 中的每个点到 p2 中的每个点并且不想像我之前的评论中那样使用 scipy,那么您可以使用 np.apply_along_axis 和 numpy.linalg.norm 来更快地完成它那么你的“最快”解决方案。
      • 以前版本的 NumPy 的规范实现非常缓慢。在当前版本中,不需要所有这些。
      【解决方案7】:
      import numpy as np
      # any two python array as two points
      a = [0, 0]
      b = [3, 4]
      

      您首先将列表更改为 numpy 数组,然后这样做:print(np.linalg.norm(np.array(a) - np.array(b)))。第二种方法直接来自python列表:print(np.linalg.norm(np.subtract(a,b)))

      【讨论】:

        【解决方案8】:

        使用 Python 3.8,这很容易。

        https://docs.python.org/3/library/math.html#math.dist

        math.dist(p, q)
        

        返回两个点 p 和 q 之间的欧几里得距离,每个给定 作为坐标序列(或可迭代)。两点必须有 相同的维度。

        大致相当于:

        sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

        【讨论】:

          【解决方案9】:

          自 Python 3.8 起

          从 Python 3.8 开始,math 模块包含函数 math.dist()
          见这里https://docs.python.org/3.8/library/math.html#math.dist

          ma​​th.dist(p1, p2)
          返回两点 p1 和 p2 之间的欧几里得距离, 每个都作为坐标序列(或可迭代)给出。

          import math
          print( math.dist( (0,0),   (1,1)   )) # sqrt(2) -> 1.4142
          print( math.dist( (0,0,0), (1,1,1) )) # sqrt(3) -> 1.7321
          

          【讨论】:

            【解决方案10】:

            Python 3.8 开始,math 模块直接提供了dist 函数,该函数返回两点之间的欧式距离(以元组或坐标列表的形式给出):

            from math import dist
            
            dist((1, 2, 6), (-2, 3, 2)) # 5.0990195135927845
            

            如果您正在使用列表:

            dist([1, 2, 6], [-2, 3, 2]) # 5.0990195135927845
            

            【讨论】:

              【解决方案11】:

              我喜欢np.dot(点积):

              a = numpy.array((xa,ya,za))
              b = numpy.array((xb,yb,zb))
              
              distance = (np.dot(a-b,a-b))**.5
              

              【讨论】:

                【解决方案12】:

                我想用各种性能说明来阐述简单的答案。 np.linalg.norm 可能会做的比你需要的更多:

                dist = numpy.linalg.norm(a-b)
                

                首先 - 此函数旨在处理列表并返回所有值,例如比较从pA 到点集sP 的距离:

                sP = set(points)
                pA = point
                distances = np.linalg.norm(sP - pA, ord=2, axis=1.)  # 'distances' is a list
                

                记住几件事:

                • Python 函数调用很昂贵。
                • [常规] Python 不缓存名称查找。

                所以

                def distance(pointA, pointB):
                    dist = np.linalg.norm(pointA - pointB)
                    return dist
                

                并不像看起来那么无辜。

                >>> dis.dis(distance)
                  2           0 LOAD_GLOBAL              0 (np)
                              2 LOAD_ATTR                1 (linalg)
                              4 LOAD_ATTR                2 (norm)
                              6 LOAD_FAST                0 (pointA)
                              8 LOAD_FAST                1 (pointB)
                             10 BINARY_SUBTRACT
                             12 CALL_FUNCTION            1
                             14 STORE_FAST               2 (dist)
                
                  3          16 LOAD_FAST                2 (dist)
                             18 RETURN_VALUE
                

                首先 - 每次我们调用它时,我们都必须对“np”进行全局查找,对“linalg”进行范围查找和对“norm”进行范围查找,以及仅调用的开销 em> 函数相当于几十条python指令。

                最后,我们浪费了两个操作来存储结果并重新加载它以返回......

                改进的第一步:加快查找速度,跳过存储

                def distance(pointA, pointB, _norm=np.linalg.norm):
                    return _norm(pointA - pointB)
                

                我们得到了更加精简:

                >>> dis.dis(distance)
                  2           0 LOAD_FAST                2 (_norm)
                              2 LOAD_FAST                0 (pointA)
                              4 LOAD_FAST                1 (pointB)
                              6 BINARY_SUBTRACT
                              8 CALL_FUNCTION            1
                             10 RETURN_VALUE
                

                不过,函数调用开销仍然需要一些工作。而且您需要进行基准测试以确定您自己是否可以更好地进行数学计算:

                def distance(pointA, pointB):
                    return (
                        ((pointA.x - pointB.x) ** 2) +
                        ((pointA.y - pointB.y) ** 2) +
                        ((pointA.z - pointB.z) ** 2)
                    ) ** 0.5  # fast sqrt
                

                在某些平台上,**0.5math.sqrt 快。您的里程可能会有所不同。

                **** 高级性能说明。

                你为什么要计算距离?如果唯一的目的是展示它,

                 print("The target is %.2fm away" % (distance(a, b)))
                

                继续前进。但是,如果您要比较距离、进行范围检查等,我想添加一些有用的性能观察。

                让我们采取两种情况:按距离排序或从列表中剔除满足范围约束的项目。

                # Ultra naive implementations. Hold onto your hat.
                
                def sort_things_by_distance(origin, things):
                    return things.sort(key=lambda thing: distance(origin, thing))
                
                def in_range(origin, range, things):
                    things_in_range = []
                    for thing in things:
                        if distance(origin, thing) <= range:
                            things_in_range.append(thing)
                

                我们需要记住的第一件事是,我们使用Pythagoras 来计算距离(dist = sqrt(x^2 + y^2 + z^2)),因此我们进行了很多sqrt 调用。数学 101:

                dist = root ( x^2 + y^2 + z^2 )
                :.
                dist^2 = x^2 + y^2 + z^2
                and
                sq(N) < sq(M) iff M > N
                and
                sq(N) > sq(M) iff N > M
                and
                sq(N) = sq(M) iff N == M
                

                简而言之:在我们真正需要以 X 而不是 X^2 为单位的距离之前,我们可以消除计算中最困难的部分。

                # Still naive, but much faster.
                
                def distance_sq(left, right):
                    """ Returns the square of the distance between left and right. """
                    return (
                        ((left.x - right.x) ** 2) +
                        ((left.y - right.y) ** 2) +
                        ((left.z - right.z) ** 2)
                    )
                
                def sort_things_by_distance(origin, things):
                    return things.sort(key=lambda thing: distance_sq(origin, thing))
                
                def in_range(origin, range, things):
                    things_in_range = []
                
                    # Remember that sqrt(N)**2 == N, so if we square
                    # range, we don't need to root the distances.
                    range_sq = range**2
                
                    for thing in things:
                        if distance_sq(origin, thing) <= range_sq:
                            things_in_range.append(thing)
                

                太好了,这两个函数都不再做任何昂贵的平方根了。那会快很多。我们还可以通过将 in_range 转换为生成器来改进它:

                def in_range(origin, range, things):
                    range_sq = range**2
                    yield from (thing for thing in things
                                if distance_sq(origin, thing) <= range_sq)
                

                如果您正在执行以下操作,这尤其有好处:

                if any(in_range(origin, max_dist, things)):
                    ...
                

                但如果你接下来要做的事情需要一段距离,

                for nearby in in_range(origin, walking_distance, hotdog_stands):
                    print("%s %.2fm" % (nearby.name, distance(origin, nearby)))
                

                考虑产生元组:

                def in_range_with_dist_sq(origin, range, things):
                    range_sq = range**2
                    for thing in things:
                        dist_sq = distance_sq(origin, thing)
                        if dist_sq <= range_sq: yield (thing, dist_sq)
                

                如果您可能会链接范围检查(“查找 X 附近和 Y 的 Nm 范围内的东西”,因为您不必再​​次计算距离),这将特别有用。

                但是,如果我们正在搜索一个非常大的 things 列表并且我们预计其中有很多不值得考虑呢?

                其实有一个很简单的优化:

                def in_range_all_the_things(origin, range, things):
                    range_sq = range**2
                    for thing in things:
                        dist_sq = (origin.x - thing.x) ** 2
                        if dist_sq <= range_sq:
                            dist_sq += (origin.y - thing.y) ** 2
                            if dist_sq <= range_sq:
                                dist_sq += (origin.z - thing.z) ** 2
                                if dist_sq <= range_sq:
                                    yield thing
                

                这是否有用将取决于“事物”的大小。

                def in_range_all_the_things(origin, range, things):
                    range_sq = range**2
                    if len(things) >= 4096:
                        for thing in things:
                            dist_sq = (origin.x - thing.x) ** 2
                            if dist_sq <= range_sq:
                                dist_sq += (origin.y - thing.y) ** 2
                                if dist_sq <= range_sq:
                                    dist_sq += (origin.z - thing.z) ** 2
                                    if dist_sq <= range_sq:
                                        yield thing
                    elif len(things) > 32:
                        for things in things:
                            dist_sq = (origin.x - thing.x) ** 2
                            if dist_sq <= range_sq:
                                dist_sq += (origin.y - thing.y) ** 2 + (origin.z - thing.z) ** 2
                                if dist_sq <= range_sq:
                                    yield thing
                    else:
                        ... just calculate distance and range-check it ...
                

                再一次,考虑让出 dist_sq。我们的热狗示例就变成了:

                # Chaining generators
                info = in_range_with_dist_sq(origin, walking_distance, hotdog_stands)
                info = (stand, dist_sq**0.5 for stand, dist_sq in info)
                for stand, dist in info:
                    print("%s %.2fm" % (stand, dist))
                

                【讨论】:

                • 为什么不给numpy添加这样一个优化的函数呢? pandas 的扩展也非常适合stackoverflow.com/questions/47643952/… 这样的问题
                • 我编辑了您的第一个数学距离方法。您使用的是不存在的pointZ。我认为您的意思是三维空间中的两个点,我进行了相应的编辑。如果我错了,请告诉我。
                【解决方案13】:

                首先找出两个矩阵的差异。然后,使用 numpy 的 multiply 命令应用逐元素乘法。之后,找到元素明智相乘的新矩阵的总和。最后求和的平方根。

                def findEuclideanDistance(a, b):
                    euclidean_distance = a - b
                    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
                    euclidean_distance = np.sqrt(euclidean_distance)
                    return euclidean_distance
                

                【讨论】:

                  【解决方案14】:

                  计算多维空间的欧几里得距离:

                   import math
                  
                   x = [1, 2, 6] 
                   y = [-2, 3, 2]
                  
                   dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
                   5.0990195135927845
                  

                  【讨论】:

                    【解决方案15】:

                    在 SciPy 中有一个函数。它叫做Euclidean

                    例子:

                    from scipy.spatial import distance
                    a = (1, 2, 3)
                    b = (4, 5, 6)
                    dst = distance.euclidean(a, b)
                    

                    【讨论】:

                    • 如果你追求效率,最好使用 numpy 函数。 scipy 距离是 numpy.linalg.norm(a-b) (和 numpy.sqrt(numpy.sum((a-b)**2)))的两倍。在我的机器上,scipy (v0.15.1) 和 numpy (v1.9.2) 分别为 19.7 µs 和 8.9 µs。在许多情况下没有相关差异,但如果在循环中可能会变得更加重要。快速浏览一下 scipy 代码,它似乎更慢,因为它在计算距离之前验证了数组。
                    • @MikePalmice 是的,scipy 函数与 numpy 完全兼容。但是看看 aigold 在这里建议的内容(当然也适用于 numpy 数组)
                    • @Avision 不确定它是否对我有用,因为我的矩阵有不同的行数;试图减去它们得到一个矩阵是行不通的
                    • @MikePalmice 你到底想用这两个矩阵计算什么?预期的输入/输出是什么?
                    • ty 用于跟进。这里有一个描述:stats.stackexchange.com/questions/322620/…。我有 2 个“操作”表;每个都有一个“代码”标签,但两组标签完全不同。我的目标是从第二个表中找到与第一个表中的固定代码相对应的最佳或最接近的代码(我知道手动检查的答案应该是什么,但以后想扩展到数百个表)。所以第一个子集是固定的;我计算 avg euclid dist bw 这个和第二个的所有代码子集,然后排序
                    【解决方案16】:

                    我在 matplotlib.mlab 中找到了一个“dist”函数,但我认为它不够方便。

                    我把它贴在这里仅供参考。

                    import numpy as np
                    import matplotlib as plt
                    
                    a = np.array([1, 2, 3])
                    b = np.array([2, 3, 4])
                    
                    # Distance between a and b
                    dis = plt.mlab.dist(a, b)
                    

                    【讨论】:

                    • 这不再适用。 (mpl 3.0)
                    【解决方案17】:

                    可以像下面这样完成。我不知道它有多快,但它没有使用 NumPy。

                    from math import sqrt
                    a = (1, 2, 3) # Data point 1
                    b = (4, 5, 6) # Data point 2
                    print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))
                    

                    【讨论】:

                    • 直接在 python 中做数学不是一个好主意,因为 python 很慢,特别是for a, b in zip(a, b)。但仍然有用。
                    • 你甚至不需要压缩 a 和 b。 sqrt(sum( (a - b)**2)) 可以解决问题。顺便说一句,答案很好
                    【解决方案18】:

                    this problem solving method 的另一个实例:

                    def dist(x,y):   
                        return numpy.sqrt(numpy.sum((x-y)**2))
                    
                    a = numpy.array((xa,ya,za))
                    b = numpy.array((xb,yb,zb))
                    dist_a_b = dist(a,b)
                    

                    【讨论】:

                    • 你可以使用 numpy 的 sqrt 和/或 sum 实现吗?这应该让它更快(?)。
                    • 我在互联网的另一边找到了这个norm = lambda x: N.sqrt(N.square(x).sum())norm(x-y)
                    • 从头开始。它必须在某个地方。在这里:numpy.linalg.norm(x-y)
                    【解决方案19】:

                    您可以轻松使用公式

                    distance = np.sqrt(np.sum(np.square(a-b)))
                    

                    实际上只是使用毕达哥拉斯定理计算距离,通过将Δx,Δy和Δz的平方相加并将结果求根。

                    【讨论】:

                      【解决方案20】:
                      import math
                      
                      dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)
                      

                      【讨论】:

                      • Python 3.8+ math.hypot() 不限于二维。 dist = math.hypot( xa-xb, ya-yb, za-zb )
                      【解决方案21】:
                      import numpy as np
                      from scipy.spatial import distance
                      input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
                      test_case = np.array([0,0,0])
                      dst=[]
                      for i in range(0,6):
                          temp = distance.euclidean(test_case,input_arr[i])
                          dst.append(temp)
                      print(dst)
                      

                      【讨论】:

                      【解决方案22】:

                      ab 定义为您定义的它们,您也可以使用:

                      distance = np.sqrt(np.sum((a-b)**2))
                      

                      【讨论】:

                        【解决方案23】:

                        以下是 Python 中欧几里得距离的一些简明代码,给定两个点,在 Python 中表示为列表。

                        def distance(v1,v2): 
                            return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)
                        

                        【讨论】:

                        • Numpy 也接受列表作为输入(无需显式传递 numpy 数组)
                        猜你喜欢
                        • 2015-09-23
                        • 2018-08-26
                        • 1970-01-01
                        • 2015-04-25
                        • 2021-01-31
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多