【问题标题】:Turn Numpy Array of Points into Numpy Array of Distances将 Numpy 点数组转换为 Numpy 距离数组
【发布时间】:2018-05-01 00:56:23
【问题描述】:

如果给定"starting_point""list_of_points",我们如何创建一个新的numpy数组“distances”,其中包含“starting_point”和“list_of_points”中每个点之间的距离?

我尝试通过使用以下代码循环 "list_of_points" 来做到这一点,但它不起作用:

distances = sqrt( (list_of_points[num][0] - starting_point[0])^2 + list_of_points[num][1] - starting_point[1])^2 ) for num in range (0,4)

starting_point = np.array([1.0, 2.0])

list_of_points = np.array([-5.0, -3.0], [-4.0, 2.0], [7.0, 8.0], [6.0, -9.0])  

distances = np.array([ d1 ], [ d2 ], [ d3 ], [ d4 ]) 

【问题讨论】:

  • 你的代码的第一个问题是你的括号不平衡,所以整个事情是一个 SyntaxError。第二个问题是^2不是均方,而是异或2;你想要**2。您的第三个问题是 list_of_points 不是有效的数组构造函数。
  • 无论如何,你很少想在 numpy 中循环;这违背了使用它的全部目的。你可能想要sqrt((list_of_points[:,0] - starting_point[0])** 2 + (list_of_points[:,1] - starting_point[1])**2) 之类的东西。或者,更好的是,查找np.hypotnp.linalg.normscipy.spatial.distance 等。
  • 如果不使用循环,如何遍历所有“list_of_points”来创建“距离”?
  • numpy 的全部意义在于它的所有操作都是元素级的。您只需执行list_of_points[:,0] - starting_point[0],它就会返回一个包含所有差异的数组。如果你不明白,你需要在继续之前阅读基本的 numpy 教程。
  • 你也可以使用einsum,它非常灵活。有很多例子……例如stackoverflow.com/questions/46571624/…

标签: python numpy


【解决方案1】:

您在使用 Numpy 时走在正确的轨道上。当我第一次使用 Numpy 时,我个人发现它非常不直观,但是通过练习它变得(有点)容易。

基本思想是要避免循环并使用矢量化操作。这使得对大型数据结构的操作快得多

矢量化的一部分是broadcasting — Numpy 可以对不同形状的对象应用操作。因此,在这种情况下,您可以在不循环的情况下进行减法:

import numpy as np
starting_point = np.array([1.0, 2.0])
list_of_points = np.array([[4, 6], [5, 5], [3, 2]]) 

# subtract starting_point from each point in list_of_points
dif = list_of_points - starting_point

如果您在文档中进行挖掘,您会发现各种矢量化操作,包括 np.linalg.norm() (docs),它计算不同类型的规范,包括距离。使用它的技巧是弄清楚要使用哪个轴。我已经更改了这些值,以便于确认正确答案:

import numpy as np
starting_point = np.array([1.0, 2.0])
list_of_points = np.array([[4, 6], [5, 5], [3, 2]])
np.linalg.norm(starting_point - list_of_points, axis=1)

# array([ 5.,  5.,  2.])

如果您愿意,您也可以通过平方、求和和取平方根来实现这一点:

np.sqrt(
    np.sum(
        np.square(list_of_points - starting_point),
    axis = 1)
)
# array([ 5.,  5.,  2.])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2017-03-08
    • 1970-01-01
    • 2021-12-18
    • 2019-08-30
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多