I have a numpy array that I am using to complete a nearest neighbor calculation:
我有一个numpy数组,我用来完成最近邻居计算:
def all_distance_compute(matrix, vector):
diff = matrix[0:] - matrix[vector]
distances = np.sqrt(np.sum(diff**2, axis=1))
for i in range(len(distances)):
print i
print distances[i]
return distances
It seems to be working based on the result distances that is returned, however, I don't know how to look at all of the values in distances and return which element in the array is the minimum.
它似乎是基于返回的结果距离工作,但是,我不知道如何查看距离中的所有值并返回数组中的哪个元素是最小值。
The for loop that I have in my function is purely for diagnostics, but I was thinking I could iterate thru this way and perhaps determine the minimum this way, but I also figured numpy probably has a better means of doing this. EDIT: So as I was typing out the question, I figured I would try my suggestion of iterating to find the minimum, and I changed my function to be this: code
我在我的函数中的for循环纯粹是用于诊断,但我认为我可以通过这种方式迭代,也许确定这种方式的最小值,但我也认为numpy可能有更好的方法来做到这一点。编辑:所以当我输入问题时,我想我会尝试迭代找到最小值的建议,我改变了我的功能:代码
for i in range(len(distances)):
if distances[i] < min and distances[i] > 0:
min = distances[i]
mindex = i
return min, mindex
1 个解决方案
#1
1
numpy.argsort
will return you the array index sorted in ascending order.
numpy.argsort将返回按升序排序的数组索引。
For example:
In [1]: import numpy as np
In [2]: arr = np.array([5,3,8,2,1,9])
In [3]: np.argsort(arr)
Out [3]: array([4, 3, 1, 0, 2, 5])
In [4]: arr[np.argsort(arr)]
Out [4]: array([1, 2, 3, 5, 8, 9])
#1
1
numpy.argsort
will return you the array index sorted in ascending order.
numpy.argsort将返回按升序排序的数组索引。
For example:
In [1]: import numpy as np
In [2]: arr = np.array([5,3,8,2,1,9])
In [3]: np.argsort(arr)
Out [3]: array([4, 3, 1, 0, 2, 5])
In [4]: arr[np.argsort(arr)]
Out [4]: array([1, 2, 3, 5, 8, 9])