When you move to a new city and look for a good restaurant, you do not study cuisine theory. You ask the people who live closest to you what they like. If most of your neighbours recommend the same place, you go there. The k nearest neighbors algorithm, usually shortened to KNN, makes predictions in exactly this way.
KNN is one of the simplest algorithms in machine learning. It has no training phase in the usual sense. It stores the data, and when a new point arrives, it finds the k closest points in the stored data and lets them decide. For classification, the neighbours vote for a class. For regression, their values are averaged. Because of this, KNN is called a lazy learner: it does no work until it has to predict.
In this tutorial, we explain how KNN works with a small picture example, then look at the three common ways of measuring distance, which are Euclidean, Manhattan and Hamming. We then cover the most important choice in KNN, the value of k, and why feature scaling can decide whether the algorithm works at all. A complete Python program follows, with output from a real run. We end with strengths, limitations, common mistakes and a short FAQ.
KNN is a supervised learning algorithm that predicts the label of a new point from the labels of its closest points in the training data. It makes no assumption about the shape of the data, which is why it is called non parametric. It has been used since the early days of pattern recognition and is still a handy first model, especially as a baseline.
The k in the name is the number of neighbours that get a vote. Its value is the main setting you control.
Consider a plot with two groups of points, red stars and blue squares, and a new green circle whose class we do not know.


For regression, the last step changes. Instead of voting, the algorithm takes the average of the neighbours’ values.
Everything in KNN depends on how distance is measured. Three measures are most common.
This is the straight line distance between two points, the one you would measure with a ruler. It is calculated by squaring the difference in each feature, adding the squares and taking the square root. It is the default for continuous numbers such as height, weight or temperature.

This is the distance you would travel in a city laid out in blocks, moving only along the grid. It adds up the absolute difference in each feature, without squaring. It is less affected by one very large difference, so it can work better when the data has outliers or many features.

This is used for categorical data, such as colour or yes and no answers. It simply counts the number of features where the two points differ. If a feature matches, it adds 0. If it does not, it adds 1. For example, two records that agree on three of four categories have a Hamming distance of 1.

| Distance | Best for | Watch out for |
|---|---|---|
| Euclidean | Continuous numbers on the same scale | Large values dominate, so scale first |
| Manhattan | Many features, or data with outliers | Less natural for real world straight line distance |
| Hamming | Categorical features | Ignores how different the categories are |
The value of k changes the result more than anything else.
A few practical rules help. For two class problems, choose an odd k, so votes cannot tie. Do not guess. Try a range of values and pick the one with the best score on data the model has not trained on. The usual tool is cross validation, which repeats the test on several splits so one lucky split does not decide.
The classic way to see this is the elbow method. Plot the error rate for each k. The error often drops fast, then flattens. The point where it stops improving much is a good choice.

Because KNN is based on distance, features with big numbers dominate. If one feature is income in rupees and another is age in years, a difference of 10,000 in income swamps a difference of 20 in age, and age is effectively ignored. Scaling puts every feature on a comparable range before distances are calculated. In the program below, the same model scores 0.722 without scaling and 0.963 with it, which is a very large jump from one line of preparation.
One more point is easy to get wrong. Fit the scaler on the training data only, and then apply it to the test data. If you fit the scaler on the test data as well, information from the test set leaks into the model, and your score becomes too optimistic.
This program uses the Wine dataset that comes with scikit learn, which has 178 wines described by 13 chemical measurements and labelled with one of three types. It has three parts: a test of scaling, a search for the best k using cross validation, and a grid search over k, the distance measure and the voting style.
When I ran the program, the first part printed:
The test set has 54 wines, so that is 39 correct against 52 correct. The Wine data is a good example because one measurement, proline, runs into the hundreds while others are below 1. Without scaling, proline decides almost everything.
The second part tried the odd values of k from 1 to 21 using 5 fold cross validation on the training set:

The last part searched k, the distance measure and the weighting together. The weights setting decides whether every neighbour counts equally or closer neighbours count more:
The grid search chose Manhattan distance, 9 neighbours and distance weighting, and scored 0.981 on the test set, or 53 of 54 wines. That is one wine better than the plain scaled model, so it is a small gain. It is a useful example of the method, and not proof that Manhattan beats Euclidean in general.
The original page uses a regression version, so here is how it differs. Use KNeighborsRegressor, which predicts the average of the k nearest values. Judge it with an error measure such as RMSE, the square root of the average squared error, and not with accuracy. The rules about scaling, choosing k and fitting the scaler on training data only stay exactly the same.
One caution applies to grid search. GridSearchCV uses the model’s default score, which for a regressor is R squared, not RMSE. If you want to choose k by RMSE, set the scoring option to neg_root_mean_squared_error. Otherwise the two methods can pick different values of k.
KNN is simple, honest and easy to explain. It asks one question: who are your closest neighbours? Run the program above on your own data, scale before you measure distance, and choose k with cross validation. If predictions turn out too slow or accuracy plateaus, that is the time to look at models such as SVM or random forest.