0

I want to see if I can modify the weight of the metric in KNeighborsClassifier. The L2 Euclidean metric works like this :

x = np.array([1,2,3])
y = np.array([6,5,4])

def d(x,y)=
  sqrt((x[0]-y[0])^2 + (x[1]-y[1])^2 + (x[2]-y[2])^2)

But what if I want to add weighting, say [1,2,3] to the L2 metric? For example,

w = np.array([1,2,3])
def d2(x,y)=
  sqrt(w[0]*(x[0]-y[0])^2 + w[1]*(x[1]-y[1])^2 + w[2]*(x[2]-y[2])^2)

Is there anything I can do with the metric or metric_params in

KNeighborsClassifier(n_neighbors=5, weights='uniform', p=2, metric='minkowski', metric_params=None, **kwargs)

Thanks

wong.lok.yin
  • 849
  • 1
  • 5
  • 10
  • You should be able to pass your own metric using the `metric` when calling `KNeighborsClassifier` – CutePoison Dec 18 '19 at 10:07
  • 1
    you can pass d2(youre distance function) in `metric` parameter see reference answer [here](https://stackoverflow.com/a/35520524/6075699) - `KNeighborsClassifier(n_neighbors=5, weights='uniform', p=2, metric=d2)` – Dishin H Goyani Dec 18 '19 at 10:25
  • Does this answer your question? [How to use a user defined metric for nearest neighbors in scikit-learn?](https://stackoverflow.com/questions/35518403/how-to-use-a-user-defined-metric-for-nearest-neighbors-in-scikit-learn) – PV8 Dec 18 '19 at 10:42

1 Answers1

0

Yes there is something.

In documentation there is an argument

> metric_params--- dict, optional (default = None) Additional keyword arguments for the metric function.

For sklearn l2 you Can not specify weights, but for some other metrics or your own version you can

Noah Weber
  • 312
  • 2
  • 13