加权欧氏距离

2024-07-02 13:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用SciPy来计算欧几里得距离

dis = scipy.spatial.distance.euclidean(A,B)

其中,A,B是5维位向量。它现在工作得很好,但是如果我为每个维度添加权重,是否仍然可以使用scipy?在

我现在拥有的:sqrt((a1-b1)^2 + (a2-b2)^2 +...+ (a5-b5)^2)

我想要的是:sqrt(w1(a1-b1)^2 + w2(a2-b2)^2 +...+ w5(a5-b5)^2)使用scipy或numpy或任何其他有效的方法来实现这一点。在

谢谢


Tags: a2距离a1scipysqrtb2spatialb1
3条回答

只需自己定义。像这样的方法应该可以做到:

def mynorm(A, B, w):
    import numpy as np
    q = np.matrix(w * (A - B))
    return np.sqrt((q * q.T).sum())

如果你想继续使用scipy函数,你可以像这样预处理向量。在

def weighted_euclidean(a, b, w):
    A = a*np.sqrt(w)
    B = b*np.sqrt(w)
    return scipy.spatial.distance.euclidean(A, B)

但是它看起来比

^{pr2}$

编写自己的加权L2范数的建议很好,但是this answer中提供的计算是不正确的。如果目的是计算

enter image description here

这样就可以做到:

def weightedL2(a,b,w):
    q = a-b
    return np.sqrt((w*q*q).sum())

相关问题 更多 >