I'm trying to build an item-based recommender using k-nn. I have a list of items, all of which have some properties (features) in common.

item    var_1      var_2    var_3        var_4          var_5
item_1  0.171547232  a      0.908855471  0.292061808    0.285678293
item_2  0.131694336  b      0.432665234  0.501300418    0.756824175
item_3  0.144318764  b      0.238752071  0.487600679    0.203133779
item_4  0.249241125  b      0.921229689  0.003638622    0.606875991
item_5  0.414306046  b      0.190824352  0.937412611    0.1789091
item_6  0.909501131  c      0.847112499  0.548322302    0.060136059
item_7  0.37469644   c      0.282628025  0.211128351    0.125910578
item_8  0.308634676  d      0.174650423  0.705026302    0.440098246
item_9  0.039294192  d      0.877086507  0.756817338    0.089838708
item_10 0.1641442    d      0.595879033  0.376224097    0.733153096 

Based on a random item input, I would like to find the top $10$ similar items using the k-nn algorithm and use them as a recommendation. However, I would also like to weight var_3 inversely proportional, hence when the value of var_3 is lower the item comes higher in the ranking of items suggested.

Do you have any suggestions on how to approach this?

  • 1
    $\begingroup$ Distance metrics (usually?) assume the same scale for all dimensions. Simply dividing var_3 by a number higher than 1 would reduce its weight. $\endgroup$
    – Mephy
    Commented Jul 13, 2019 at 14:14

1 Answer 1


You can define a custom distance metric using the metric parameter from sklearns KNeighborsClassifier where you can specify your callable function that gets called when calculating the distances from the algorithm. There you can weigh var_3 inversely proportional.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.