Is there a Python Function to specify the weights I want to use for KNN?

I am using the scikit-learn KNeighbors Regressor in Python. I was reading an article where they defined that k was 3 and the nearest neighbor was weighted 50% but the further two were weighted 30% and 20%, respectively. I have been looking all over for documentation on how to do something of the sort using callable weights but I am not finding much regarding how to write a callable function like this. Do you have any ideas?

1 answer

  • answered 2022-03-02 22:54 Acccumulation

    class sklearn.neighbors.KNeighborsClassifier(n_neighbors=5, *, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None)
    weights{‘uniform’, ‘distance’} or callable, default=’uniform’ Weight function used in prediction. Possible values:
    ‘uniform’ : uniform weights. All points in each neighborhood are weighted equally.
    ‘distance’ : weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away.
    [callable] : a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum