pdist 및 squareform과 함께 nparray를 사용하여 거리 행렬 생성
-
24-12-2019 - |
문제
DBSCAN(scikit 학습 구현) 및 위치 데이터를 사용하여 클러스터링을 시도하고 있습니다.내 데이터는 np 배열 형식이지만 Haversine 공식과 함께 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
는 사용자 정의 거리 함수를 통과 할 수 없습니다. 문서 에는 몇 가지 옵션이 있지만 Haverside 거리는 지원되는 메트릭 목록이 아닙니다.
계산을 "수동으로"해야합니다. 즉, 이와 같은 루프가 있습니다.
from numpy import array,zeros
def haversine(lon1, lat1, lon2, lat2):
""" See the link below for a possible implementation """
pass
#example input (your's, truncated)
ResultArray = array([[ 53.3252628, -6.2644198 ],
[ 53.3287395 , -6.2646543 ],
[ 53.33321202 , -6.24785807],
[ 53.3253074 , -6.2644483 ]])
N = ResultArray.shape[0]
distance_matrix = zeros((N, N))
for i in xrange(N):
for j in xrange(N):
lati, loni = ResultArray[i]
latj, lonj = ResultArray[j]
distance_matrix[i, j] = haversine(loni, lati, lonj, latj)
distance_matrix[j, i] = distance_matrix[i, j]
print distance_matrix
[[ 0. 0.38666203 1.41010971 0.00530489]
[ 0.38666203 0. 1.22043364 0.38163748]
[ 1.41010971 1.22043364 0. 1.40848782]
[ 0.00530489 0.38163748 1.40848782 0. ]]
.
다른 팁
scipy를 사용하면이 링크 편의를 위해 여기에보고되었습니다.
.Y = pdist(X, f)
Computes the distance between all pairs of vectors in X using the user supplied 2-arity function f. For example, Euclidean distance between the vectors could be computed as follows:
dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))
.
여기 에서이 "noreferrer">에서 코드에서 영감을받은 코드 버전을보고합니다.링크 :
from numpy import sin,cos,arctan2,sqrt,pi # import from numpy
# earth's mean radius = 6,371km
EARTHRADIUS = 6371.0
def getDistanceByHaversine(loc1, loc2):
'''Haversine formula - give coordinates as a 2D numpy array of
(lat_denter link description hereecimal,lon_decimal) pairs'''
#
# "unpack" our numpy array, this extracts column wise arrays
lat1 = loc1[1]
lon1 = loc1[0]
lat2 = loc2[1]
lon2 = loc2[0]
#
# convert to radians ##### Completely identical
lon1 = lon1 * pi / 180.0
lon2 = lon2 * pi / 180.0
lat1 = lat1 * pi / 180.0
lat2 = lat2 * pi / 180.0
#
# haversine formula #### Same, but atan2 named arctan2 in numpy
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2.0))**2
c = 2.0 * arctan2(sqrt(a), sqrt(1.0-a))
km = EARTHRADIUS * c
return km
.
다음과 같은 방법으로 호출 :
D = spatial.distance.pdist(A, lambda u, v: getDistanceByHaversine(u,v))
.
내 구현에서 행렬 A는 첫 번째 열로 경도 값과 두 번째 열로 표준 값이 10 진수로 표시됩니다.
이제 scipy를 사용하여 거리 행렬을 미리 계산하지 않고도 scikit-learn의 DBSCAN 및 Haversine 측정항목을 사용하여 공간 위도-경도 데이터를 클러스터링할 수 있습니다.
db = DBSCAN(eps=2/6371., min_samples=5, algorithm='ball_tree', metric='haversine').fit(np.radians(coordinates))
이것은 이 튜토리얼에서 나온 것입니다. scikit-learn DBSCAN을 사용하여 공간 데이터 클러스터링.특히, eps
값은 2km를 6371(지구 반경(km))로 나누어 라디안으로 변환합니다.또한, .fit()
Haversine 미터법에 대해 라디안 단위로 좌표를 사용합니다.