Python最近邻坐标

2024-10-01 17:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查一下我是否正确地使用了scipy的KD树,因为它看起来比简单的bruteforce慢。在

关于这一点,我有三个问题:

第一季度。

如果我创建以下测试数据:

nplen = 1000000
# WGS84 lat/long
point = [51.349,-0.19]
# This contains WGS84 lat/long
points = np.ndarray.tolist(np.column_stack(
        [np.round(np.random.randn(nplen)+51,5),
         np.round(np.random.randn(nplen),5)]))

并创建三个功能:

^{pr2}$

我希望cKD树是最快的,但是-运行这个:

print("Co-ordinate: ", f(points,point))
print("Index: ", points.index(list(f(points,point))))
%timeit f(points,point)

结果时间-简单的bruteforce方法更快:

closest_math: 1 loops, best of 3: 3.59 s per loop
ckd_test: 1 loops, best of 3: 13.5 s per loop
kd_test: 1 loops, best of 3: 30.9 s per loop

这是因为我用错了吗?在

第2季度。

我假设即使要得到最近点的排名(而不是距离),仍然需要投射数据。然而,似乎投影点和未投影点给了我相同的最近邻:

def proj_list(points,
              inproj = Proj(init='epsg:4326'),
              outproj = Proj(init='epsg:27700')):
    """ Projected geo coordinates"""
    return [list(transform(inproj,outproj,x,y)) for y,x in points]
proj_points = proj_list(points)
proj_point = proj_list([point])[0]

这仅仅是因为我的点扩散不够大而导致扭曲吗?我重新运行了几次,仍然从返回的已预测和未预测的列表中获得相同的索引。在

第3季度。

与在(未投影)纬度/经度上计算haversine或vincenty距离相比,投影点(如上所述)和计算斜边距离是否更快?还有哪个选项更准确?我做了一个小测试:

from math import *
def haversine(origin,
              destination):
    """
    Find distance between a pair of lat/lng coordinates
    """
    lat1, lon1, lat2, lon2 = map(radians, [origin[0],origin[1],destination[0],destination[1]])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * asin(sqrt(a))
    r = 6371000  # Metres
    return (c * r)

def closest_math_unproj(points,point):
    """ Haversine on unprojected """
    return (min((haversine(point,pt),pt[0],pt[1]) for pt in points))

def closest_math_proj(points,point):
    """ Simple angle since projected"""
    return (min((hypot(x2-point[1],y2-point[0]),y2,x2) for y2,x2 in points)) 

结果:

enter image description here

所以这似乎说明投影然后做距离比不投影要快-但是,我不确定哪种方法会带来更精确的结果。在

online vincenty calculation上测试这一点,似乎投影坐标是正确的方法:

enter image description here


Tags: of方法pt距离returndefnpmath
1条回答
网友
1楼 · 发布于 2024-10-01 17:35:31

问题1

k-d树明显效率低下的原因很简单:您同时测量k-d树的构造和查询。这不是您应该或者应该如何使用k-d树:您应该只构造一次。如果只测量查询,所花费的时间将减少到几十毫秒(而使用暴力方法则为几秒钟)。在

问题2

这将取决于所使用的实际数据和所使用的投影的空间分布。基于k-d树的实现在平衡构建的树方面的效率,可能会有细微的差别。如果只查询单个点,那么结果将是确定性的,并且无论如何都不受点分布的影响。在

对于您使用的示例数据(具有强烈的中心对称性)和地图投影(Transverese Mercator),差异应该可以忽略不计。在

问题3

从技术上讲,你的问题的答案是微不足道的:使用哈弗辛公式进行地理距离测量既更准确,也更慢。准确性和速度之间的权衡是否得到保证很大程度上取决于您的用例和数据的空间分布(显然,主要取决于空间范围)。在

如果点的空间范围在较小的区域一侧,那么使用适当的投影和简单的欧几里德距离度量可能对您的用例足够精确,并且比使用Haversine公式更快。在

相关问题 更多 >

    热门问题