2014-05-21 2 views
1

이것은 각 점에 대해 k- 가장 가까운 이웃에 대한 평균 거리를 계산해야하는 R n의 점에 대한 K- 가장 가까운 이웃 알고리즘입니다. 문제는 그것이 비록 내가 반복한다는 의미에서 비효율적이라고 벡터화했다는 것입니다. 누군가가 나에게이 코드를 향상시킬 수 있다면 행복 할 것 :파이썬에서 벡터화 평균 K- 인접 이웃 거리

import numpy as np 
from scipy.spatial.distance import pdist 
from scipy.spatial.distance import squareform 

def nn_args_R_n_squared(points): 
    """Calculate pairwise distances of points and return the matrix together with matrix of indices of the first matrix sorted""" 
    dist_mat=squareform(pdist(points,'sqeuclidean')) 
    return dist_mat,np.argsort(dist_mat,axis=1) 
def knn_avg_dist(X,k): 
    """Calculates for points in rows of X, the average distance of each, to their k-nearest  neighbours""" 
    X_dist_mat,X_sorted_arg=nn_args_R_n_squared(X) 
    X_matrices=(X[X_sorted_arg[:,1:k+1]]-X[...,None,...]).astype(np.float64) 
    return np.mean(np.linalg.norm(X_matrices,axis=2)**2,axis=1) 
X=np.random.randn(30).reshape((10,3)) 
print X 
print knn_avg_dist(X,3) 

출력 : 당신은 내가 두 번 거리를 계산 볼 수 있습니다,하지만 난 방법을 마련하지 못했습니다으로

[[-1.87979713 0.02832699 0.18654558] 
[ 0.95626677 0.4415187 -0.90220505] 
[ 0.86210012 -0.88348927 0.32462922] 
[ 0.42857316 1.66556448 -0.31829065] 
[ 0.26475478 -1.6807253 -1.37694585] 
[-0.08882175 -0.61925033 -1.77264525] 
[-0.24085553 0.64426394 -0.01973027] 
[-0.86926425 0.93439913 -0.31657442] 
[-0.30987468 0.02925649 -1.38556347] 
[-0.41801804 1.40210993 -1.04450895]] 
[ 3.37983833 2.1257945 3.60884158 1.67051682 2.85013297 1.66756279 
    1.2678029 1.20491026 1.54623574 1.30722388] 

동시에 각 행에서 여러 요소를 읽어야하므로 동일한 정보를 X_dist_mat에서 읽는 것이 좋습니다.

+1

당신은 그 사람이 복사 살펴 봐야 붙여 넣을 수 코드에'import's 및 더미 데이터의 생성을 추가 한 경우. 그렇지 않으면'sklearn'의 기존 구현에서 영감을 얻을 수 있어야합니다. – eickenberg

답변

2

사용 scipy.spatial.cKDTree는 :

>>> data = np.random.rand(1000, 3) 
>>> import scipy.spatial 

>>> kdt = scipy.spatial.cKDTree(data) 
>>> k = 5 # number of nearest neighbors 
>>> dists, neighs = kdt.query(data, k+1) 
>>> avg_dists = np.mean(dists[:, 1:], axis=1) 
+0

감사합니다! 당신은 파이썬 세계에서 흔들립니다! :) – Cupitor