我正试图从矢量列表中检索向量的最近邻居,使用:
neigh = NearestNeighbors(metric ='cosine')
neigh.fit(名单)
从我所看到和见证的是,如果vector1和vector2在所有维度上具有相同的精确值,则从这两个向量检索的距离将等于0.我正在使用kneighbors方法来查找距离。
neigh.neighbors(矢量输入)
但是,在某些情况下(并非所有情况),即使两个矢量相等,检索的距离也不等于0,而是一些像2.34e-16这样的微小数字。
len([i for i,j in zip(vector_from_list,vector_input)if i == j])返回列表的维度,意味着每个i-index元素等于另一个向量的i-index元素。因此,如果我没有错,那么这些向量是完全相等的。
所有向量的dtype是np.float64
找方法的方法不一致吗?或者我在scikit方法中忽略了某些东西(例如参数)?
我认为这是一种预期的行为。
如果要在距离等于零的情况下使用条件,请考虑使用numpy.isclose。例如,
import numpy as np
a = 2.34e-16
b = 1.7e-14 # both tiny values, almost zero
print(a==b) # prints False
print(np.isclose(a,b)) # prints True
您可以通过设置函数的其他参数来设置您希望值的接近程度。有关更多信息,请参阅documentation。
或者,您也可以使用python的内置函数math.isclose。见documentation。例,
import math
a = 2.34e-16
b = 1.7e-14 # both tiny values, almost zero
print(math.isclose(a,b, abs_tol=1e-10)) # True