Search code examples
pythonscikit-learnk-means

Calculate weighted distance from all points to a given point in python


I'm trying to calculate the weighted distance from a set of points to a given point. The weighted distance function looks like the following.

enter image description here

The set of points (X in the code) looks like the following

[[-14.78816795   1.        ]
 [-13.39187241   1.        ]
 [ -6.58691072   1.        ]
 ...
 [ -3.45446849  99.        ]
 [ 30.75222397  99.        ]
 [ 32.22760391  99.        ]]

and my given points (Centroids in the code) looks like the following

array([[ -0.75675046, -28.46644783,   0.76348782],
       [ 80.        ,  74.        ,  83.        ]])

for unweighted Euclidian Distance i understand that i can use the following code

k=3
for k in range(K):
       tempDist=np.sum((X-Centroids[:,k])**2,axis=1)
       EuclidianDistance=np.c_[EuclidianDistance,tempDist]

but i'm not very sure about how to apply the weight to the x and y components.


Solution

  • First of all I think you have a couple of mistakes in your unweighted Euclidian Distance. There seems to be lacking a squareroot and K is undefined.

    I have included the weights while trying to remain faithfully to the code you already had.

    greek_lambda=0.2
    W=np.array([[greek_lambda,0],[0,1-greek_lambda]])
    
    for k in range(3):
       tempDist=np.sqrt(np.sum(np.dot((X-Centroids[:,k]),W)**2,axis=1))
       EuclidianDistance=np.c_[EuclidianDistance,tempDist]
    print(EuclidianDistance)