我有一个目标数组A,代表了NCEP再分析数据中等压面的压力水平。
我还有一个云被观察到的压力长时间序列B。
我正在寻找一个k最近邻查找算法,返回最近邻居的索引,类似于Matlab中的knnsearch。在Python中可以表示为: indices, distance = knnsearch(A, B, n),其中indices是B中每个值的前n个最近的A中的索引,distance是值B与最近的A值之间的距离。数组A和B可以具有不同的长度(这是目前大多数解决方案的瓶颈,因为我必须循环遍历B中的每个值来返回我的indices和distance)。
我正在寻找一个k最近邻查找算法,返回最近邻居的索引,类似于Matlab中的knnsearch。在Python中可以表示为: indices, distance = knnsearch(A, B, n),其中indices是B中每个值的前n个最近的A中的索引,distance是值B与最近的A值之间的距离。数组A和B可以具有不同的长度(这是目前大多数解决方案的瓶颈,因为我必须循环遍历B中的每个值来返回我的indices和distance)。
import numpy as np
A = np.array([1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]) # this is a fixed 17-by-1 array
B = np.array([923, 584.2, 605.3, 153.2]) # this can be any n-by-1 array
n = 2
我希望从indices, distance = knnsearch(A, B, n)
得到以下结果:
indices = [[1, 2],[4, 5] etc...]
将 A
中的 923
匹配到第一个 A[1]=925
,然后匹配到 A[2]=850
;
将 A
中的 584.2
匹配到第一个 A[4]=600
,然后匹配到 A[5]=500
distance = [[72, 77],[15.8, 84.2] etc...]
其中,72
表示从 B
中查询的值到最近的 A
值之间的距离,例如:distance[0, 0] == np.abs(B[0] - A[1])
我想到的唯一解决方案是:
import numpy as np
def knnsearch(A, B, n):
indices = np.zeros((len(B), n))
distances = np.zeros((len(B), n))
for i in range(len(B)):
a = A
for N in range(n):
dif = np.abs(a - B[i])
ind = np.argmin(dif)
indices[i, N] = ind + N
distances[i, N] = dif[ind + N]
# remove this neighbour from from future consideration
np.delete(a, ind)
return indices, distances
array_A = np.array([1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10])
array_B = np.array([923, 584.2, 605.3, 153.2])
neighbours = 2
indices, distances = knnsearch(array_A, array_B, neighbours)
print(indices)
print(distances)
返回:
[[ 1. 2.]
[ 4. 5.]
[ 4. 3.]
[10. 11.]]
[[ 2. 73. ]
[ 15.8 84.2]
[ 5.3 94.7]
[ 3.2 53.2]]
如果我的A和B数组包含许多元素并且有许多最近的邻居,必须有一种方法可以消除for循环,以提高性能...
请帮忙!谢谢 :)