Euclidean distance with weights Euclidean distance with weights numpy numpy

Euclidean distance with weights


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

enter image description here

then this should do the job:

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


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())


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())