How to create custom distance function with weighted values as vectors

Viewed 40

I want to create a custom distance function with 3 inputs for SKLEARN, I managed to find work around solution HERE which works perfectly. I have a vector of weights for each point in X, and I want to apply the weighting when computing the distance as shown in the image below:

enter image description here

Here is the code snippet where I tried to implement it:

from sklearn.neighbors import DistanceMetric
import numpy as np
    class distances():
        def __init__(self, w):
            self.w= w

        def weighted_hamming(self, a, b):
            return sum(a != b) * w


    x = np.random.random((4, 3))
    w = np.random.random((4, 1))
    dist = distances(w)

    dist = DistanceMetric.get_metric(metric='pyfunc', func=dist.hamming)
    dist.pairwise(x)

How do I implement it such that I don't get this error below:

TypeError: Custom distance function must accept two vectors and return a float.

1 Answers

Your weighted_hamming() doesn't return a float. It returns a vector of shape (4,1) as your w.

Related