我正在尝试使用DBSCAN(scikit learn implementation)和位置数据进行集群。我的数据是np数组格式,但是要使用DBSCAN和Haversine公式,我需要创建一个距离矩阵。当我尝试这样做时,我得到了以下错误(一个“模块”不可调用的错误)。从我在网上看到的情况来看,这是一个导入错误,但我很确定这不是我的情况。我已经建立了我自己的哈弗斯距离公式,但我确信错误不在这里。
这是我的输入数据,一个np数组(ResultArray)。
[[ 53.3252628 -6.2644198 ]
[ 53.3287395 -6.2646543 ]
[ 53.33321202 -6.24785807]
[ 53.3261015 -6.2598324 ]
[ 53.325291 -6.2644105 ]
[ 53.3281323 -6.2661467 ]
[ 53.3253074 -6.2644483 ]
[ 53.3388147 -6.2338417 ]
[ 53.3381102 -6.2343826 ]
[ 53.3253074 -6.2644483 ]
[ 53.3228188 -6.2625379 ]
[ 53.3253074 -6.2644483 ]]
这是出错的代码行。
distance_matrix = sp.spatial.distance.squareform(sp.spatial.distance.pdist
(ResultArray,(lambda u,v: haversine(u,v))))
这是错误消息:
File "Location.py", line 48, in <module>
distance_matrix = sp.spatial.distance.squareform(sp.spatial.distance.pdist
(ResArray,(lambda u,v: haversine(u,v))))
File "/usr/lib/python2.7/dist-packages/scipy/spatial/distance.py", line 1118, in pdist
dm[k] = dfun(X[i], X[j])
File "Location.py", line 48, in <lambda>
distance_matrix = sp.spatial.distance.squareform(sp.spatial.distance.pdist
(ResArray,(lambda u,v: haversine(u,v))))
TypeError: 'module' object is not callable
我将scipy导入为sp(将scipy导入为sp)
请参考@TommasoF答案。这个答案是错误的:
pdist
允许选择自定义距离函数。一旦答案不再被选为正确答案,我将删除它。只是
scipy
的pdist
不允许传入自定义距离函数。正如您可以在docs中看到的,您有一些选项,但是haverside distance不在支持的度量列表中。(不过,Matlab
pdist
确实支持该选项,请参见here)您需要“手动”进行计算,即使用循环,类似这样的操作将起作用:
作为参考,可以在Python中找到Haverside的一个实现here。
使用Scipy,您可以定义一个自定义距离函数,如本文link中的文档所建议的,并在此处报告,以方便使用:
在这里,我报告了我的代码版本,灵感来自于这个link:
并以以下方式呼叫:
在我的实现中,矩阵A的第一列是经度值,第二列是纬度值,用十进制度数表示。
现在,您可以使用scikit learn的DBSCAN和haversine度量对空间经纬度数据进行聚类,而无需使用scipy预计算距离矩阵。
这是关于clustering spatial data with scikit-learn DBSCAN的教程。特别是,注意
eps
值是2km除以6371(地球半径单位为km)将其转换为弧度。另外,请注意,.fit()
采用haversine度量的弧度单位坐标。相关问题 更多 >
编程相关推荐