K-nearest neighbor distances
Quick answer
K-nearest neighbors (KNN) classifies a new sample by looking up the labels of nearby training samples. Its predictions depend on the distance definition, the number of neighbors k, and the voting rule. Examples run locally with Python 3.13.5, scikit-learn 1.8.0, NumPy 2.3.5 and SciPy 1.17.0 when imported. ByteMind library execution is unverified.
Rank two-dimensional points
q=[2,2]rows=[[1,2],[5,4],[2,4]]print(sorted(range(len(rows)),key=lambda i:sum((a-b)**2 for a,b in zip(rows[i],q))))Expected output:
[0, 2, 1]Squared distances are 1, 13 and 4, so the ordering is 0, 2, 1.
How it works
Represent each observation as a vector of numerical features. Euclidean distance is the square root of the sum of squared coordinate differences; Manhattan distance is the sum of absolute differences. Squared Euclidean distances have the same ranking as Euclidean distances but are not interchangeable for distance weighting. For a fictional machine with vibration and temperature features, a query at (2,2) is closer to (1,2) than to (5,4). Sort distances, take k rows and vote. With uniform voting, the most frequent class wins. A toy deterministic contract can resolve equal distances by row order and equal votes by the smallest numeric class label. Real libraries may select different neighbors at the k boundary, so test ties rather than assuming this custom rule. Distance weighting instead favors closer neighbors; handle exact matches explicitly. KNN stores training examples rather than estimating a small coefficient vector. A brute-force query costs O(n*d) distance operations before selection, where n is training rows and d is dimensions; index structures may help depending on data and metric. Choose k and metric on validation data, never by repeated test evaluation. Small k can be sensitive to noise; large k can wash out local structure. K must be positive and not exceed the available training sample count.
Use uniform neighbor voting
from sklearn.neighbors import KNeighborsClassifierm=KNeighborsClassifier(n_neighbors=3,algorithm="brute").fit([[0],[2],[4],[8]],[0,1,1,0])print(m.predict([[3]]).tolist())print(m.predict_proba([[3]]).round(6).tolist())Expected output:
[1][[0.333333, 0.666667]]Two of the three nearest rows have label 1; vote fractions are not necessarily calibrated probabilities.
Common mistakes
Do not include the target or row identifier as a distance feature. Do not assume identical predictions under different feature units or tie policies. A training prediction can include the point itself, making training accuracy misleading.
Practice and next steps
For query [2,2], calculate Manhattan distances to the three points in the first example. Then implement deterministic voting. Complete the knowledge check and coding exercise. Next: Scaling and dimensionality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
K-nearest neighbor distances — knowledge check
Apply k-nearest neighbor distances to new examples.
What determines uniform KNN prediction?
Which squared Euclidean distance joins [1,2] and [4,6]?
Why specify a tie policy?
What often happens with excessively large k?
Where should k be selected?