我无法解释sklearn(20.2版本)中haversine实现的输出。
文档说:“请注意,haversine距离度量需要以[纬度、经度]的形式提供数据,并且输入和输出的单位均为弧度。”因此,我可以通过乘以6371(半径的大约估计距离)来转换为公里。
计算两点之间距离的功能如下:
def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2-lat1)
dlon = math.radians(lon2-lon1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c
return d
distance([32.027240,-81.093190],[41.981876,-87.969982])
1263.103504537151
这是正确的距离。
使用BallTree实现:
from sklearn.neighbors import BallTree
test_points = [[32.027240,41.981876],[-81.093190,-87.969982]]
tree = BallTree(test_points,metric = 'haversine')
results = tree.query_radius(test_points,r = 10,return_distance = True)
results[1]
array([array([0. , 1.53274271]), array([1.53274271, 0. ])],
dtype=object)
同样适用于距离度量实现:
dist = DistanceMetric.get_metric('haversine')
dist.pairwise([[32.027240,41.981876],[-81.093190,-87.969982]])
array([[0. , 1.53274271],
[1.53274271, 0. ]])
我还尝试过改变顺序,以防它不应该被输入为[[lat1,lat2],[lon1,lon2]],但是我也没有得到可以解释的结果。
有人知道如何使用sklearn实现获取两个坐标之间的距离(以公里为单位)吗?