我有一个np数组,X大小为1000 x 1000,其中每个元素都是一个实数。我想找到这个np数组每一行中每个点的5个最近点。这里距离度量可以只是abs(x-y)。我试过了
for i in range(X.shape[0]):
knn = NearestNeighbors(n_neighbors=5)
knn.fit(X[i])
for j in range(X.shape[1])
d = knn.kneighbors(X[i,j], return_distance=False)
然而,这对我不起作用,我不确定这是多么有效。有没有解决的办法?我已经看到很多用于比较矢量的方法,但没有用于比较单个元素的方法。我知道我可以使用for循环并循环查找k最小,但这在计算上会很昂贵。 KD树能为此工作吗?我尝试过类似
的方法Finding index of nearest point in numpy arrays of x and y coordinates
然而,我无法让它发挥作用。是否有一些我不知道可以实现这一目标的numpy功能?
答案 0 :(得分:2)
为数据的每一行构建一个带scipy.spatial.cKDTree
的kdtree。
import numpy as np
import scipy.spatial
def nearest_neighbors(arr, k):
k_lst = list(range(k + 2))[2:] # [2,3]
neighbors = []
for row in arr:
# stack the data so each element is in its own row
data = np.vstack(row)
# construct a kd-tree
tree = scipy.spatial.cKDTree(data)
# find k nearest neighbors for each element of data, squeezing out the zero result (the first nearest neighbor is always itself)
dd, ii = tree.query(data, k=k_lst)
# apply an index filter on data to get the nearest neighbor elements
closest = data[ii].reshape(-1, k)
neighbors.append(closest)
return np.stack(neighbors)
N = 1000
k = 5
A = np.random.random((N, N))
nearest_neighbors(A, k)
答案 1 :(得分:1)
我不确定你想要的最终结果。但这绝对可以满足您的需求。
np.random.seed([3,1415])
X = np.random.rand(1000, 1000)
抓住上三角形索引以跟踪每行的每个点组合
x1, x2 = np.triu_indices(X.shape[1], 1)
生成所有距离的数组
d = np.abs(X[:, x1] - X[:, x2])
找到每行最接近的5
tpos = np.argpartition(d, 5)[:, :5]
然后x1[tpos]
给出最近对中第一个点的行方位置,而x2[tpos]
给出最近对的第二个位置。
答案 2 :(得分:0)
这是一个argsort
解决方案,力求利用简单的指标:
def nn(A, k):
out = np.zeros((A.shape[0], A.shape[1] + 2*k), dtype=int)
out[:, k:-k] = np.argsort(A, axis=-1)
out[:, :k] = out[:, -k-1, None]
out[:, -k:] = out[:, k, None]
strd = stride_tricks.as_strided(
out, strides=out.strides + (out.strides[-1],), shape=A.shape + (2*k+1,))
delta = A[np.arange(A.shape[0])[:, None, None], strd]
delta -= delta[..., k, None]
delta = np.abs(delta)
s = np.argpartition(delta,(0, k), axis = -1)[..., 1:k+1]
inds = tuple(np.ogrid[:strd.shape[0], :strd.shape[1], :0][:2])
res = np.empty(A.shape + (k,), dtype=int)
res[np.arange(strd.shape[0])[:, None, None], out[:, k:-k, None],
np.arange(k)[None, None, :]] = strd[inds + (s,)]
return res
N = 1000
k = 5
r = 10
A = np.random.random((N, N))
# crude test
print(np.abs(A[np.arange(N)[:, None, None], res]-A[..., None]).mean())
# timings
print(timeit(lambda: nn(A, k), number=r) / r)
输出:
# 0.00150537172454
# 0.4567880852999224