Euclidean distance with weights

与世无争的帅哥 提交于 2020-01-02 04:44:08

问题


I am currently using SciPy to calculate the euclidean distance

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

where; A, B are 5-dimension bit vectors. It works fine now, but if I add weights for each dimension then, is it still possible to use scipy?

What I have now: sqrt((a1-b1)^2 + (a2-b2)^2 +...+ (a5-b5)^2)

What I want: sqrt(w1(a1-b1)^2 + w2(a2-b2)^2 +...+ w5(a5-b5)^2) using scipy or numpy or any other efficient way to do this.

Thanks


回答1:


The suggestion of writing your own weighted L2 norm is a good one, but the calculation provided in this answer is incorrect. If the intention is to calculate

then this should do the job:

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



回答2:


Simply define it yourself. Something like this should do the trick:

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



回答3:


If you want to keep using scipy function you could pre-process the vector like this.

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

However it's look slower than

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


来源:https://stackoverflow.com/questions/8860850/euclidean-distance-with-weights

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!