我有一个矢量列表作为numpy数组。
[[ 1., 0., 0.],
[ 0., 1., 2.] ...]
它们都具有相同的尺寸。如何在向量空间中找出哪个向量最接近数组中所有其他向量?有scipy或sklearn函数来计算吗?
Update
:
“最接近”,我的意思是余弦和欧氏距离。
Update 2
:
假设我有4个向量(a,b,c,d),向量之间的余弦距离为:
a,b = 0.2
a,c = 0.9
a,d = 0.7
b,c = 0.5
b,d = 0.75
c,d = 0.8
因此对于每一个,矢量a,b,c,d得到:
{
'a': [1,0.2,0.9,0.7],
'b': [0.2,1,0.5,0.75],
'c' : [0.9,0.5,1,0.75],
'd' : [0.7,0.75,0.8,1]
}
有没有办法说让我们说矢量d是与a,b,c最相似的那个?
答案 0 :(得分:2)
你可以强行这样做。请注意,这是O(n ^ 2),对于大n来说会慢一些。
import numpy as np
def cost_function(v1, v2):
"""Returns the square of the distance between vectors v1 and v2."""
diff = np.subtract(v1, v2)
# You may want to take the square root here
return np.dot(diff, diff)
n_vectors = 5
vectors = np.random.rand(n_vectors,3)
min_i = -1
min_cost = 0
for i in range (0, n_vectors):
sum_cost = 0.0
for j in range(0, n_vectors):
sum_cost = sum_cost + cost_function(vectors[i,:],vectors[j,:])
if min_i < 0 or min_cost > sum_cost:
min_i = i
min_cost = sum_cost
print('{} at {}: {:.3f}'.format(i, vectors[i,:], sum_cost))
print('Lowest cost point is {} at {}: {:.3f}'.format(min_i, vectors[min_i,:], min_cost))