用Python中的KMeans算法对地理位置坐标(lat,long pairs)进行聚类

2024-04-23 22:25:23 发布

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

使用以下代码将地理位置坐标分为3个簇:

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.cluster.vq import kmeans2, whiten

    coordinates= np.array([
               [lat, long],
               [lat, long],
                ...
               [lat, long]
               ])
    x, y = kmeans2(whiten(coordinates), 3, iter = 20)  
    plt.scatter(coordinates[:,0], coordinates[:,1], c=y);
    plt.show()

使用Kmeans进行位置聚类是否正确,因为它使用Euclidean distance而不是Haversine formula作为距离函数?


Tags: 代码fromimportnumpymatplotlibasnpplt
2条回答

k-means不是一个很好的用于空间聚类的算法,因为你的意思是。相反,您可以使用scikit learn的DBSCAN和haversine metric和ball tree算法来完成这个集群工作。

本教程使用DBSCAN/haversine演示clustering latitude-longitude spatial data,并避免了所有这些欧几里德距离问题:

df = pd.read_csv('gps.csv')
coords = df.as_matrix(columns=['lat', 'lon'])
db = DBSCAN(eps=eps, min_samples=ms, algorithm='ball_tree', metric='haversine').fit(np.radians(coords))

注意,这特别使用scikit learn v0.15,因为一些早期/后期版本似乎需要计算完整的距离矩阵。还要注意,eps值是以弧度为单位的,.fit()接受haversine度量的以弧度为单位的坐标。

这在很大程度上取决于您的应用程序:

  • 在赤道附近,结果应该相当准确。在接近其中一个极点时,结果将毫无用处。
  • 但是,它可以作为预处理步骤,也可以用于精度要求较低的应用程序,例如小型、不重叠和非常明显的集群。

如果您真的需要Haversine公式,您可能需要研究this讨论。正如Anony Mousse所说:

Note that Haversine distance is not appropriate for k-means or average-linkage clustering, unless you find a smart way of computing the mean that minimizes variance. Do not use the arithmetic average if you have the -180/+180 wrap-around of latitude-longitude coordinates.

相关问题 更多 >