我在研究工作中实现了一种基本的最近邻搜索算法。
事实上,基本的numpy实现效果很好,但只需添加'@jit'装饰器(使用Numba编译),输出结果就有所不同(最后出现某些邻居的重复,原因未知...)
以下是基本算法:
但是Numba编译会产生奇怪的输出:
有人可以帮忙吗?我不明白为什么会出现这种情况...谢谢。
以下是基本算法:
import numpy as np
from numba import jit
@jit(nopython=True)
def knn(p, points, k):
'''Find the k nearest neighbors (brute force) of the point p
in the list points (each row is a point)'''
n = p.size # Lenght of the points
M = points.shape[0] # Number of points
neighbors = np.zeros((k,n))
distances = 1e6*np.ones(k)
for i in xrange(M):
d = 0
pt = points[i, :] # Point to compare
for r in xrange(n): # For each coordinate
aux = p[r] - pt[r]
d += aux * aux
if d < distances[k-1]: # We find a new neighbor
pos = k-1
while pos>0 and d<distances[pos-1]: # Find the position
pos -= 1
pt = points[i, :]
# Insert neighbor and distance:
neighbors[pos+1:, :] = neighbors[pos:-1, :]
neighbors[pos, :] = pt
distances[pos+1:] = distances[pos:-1]
distances[pos] = d
return neighbors, distances
进行测试:
p = np.random.rand(10)
points = np.random.rand(250, 10)
k = 5
neighbors = knn(p, points, k)
没有使用@jit装饰器,将得到正确的答案:
In [1]: distances
Out[1]: array([ 0.3933974 , 0.44754336, 0.54548715, 0.55619749, 0.5657846 ])
但是Numba编译会产生奇怪的输出:
Out[2]: distances
Out[2]: array([ 0.3933974 , 0.44754336, 0.54548715, 0.54548715, 0.54548715])
有人可以帮忙吗?我不明白为什么会出现这种情况...谢谢。