+91 99301 12627
Machine Learning

KNN Algorithm Explained: How K-Nearest Neighbors Works (with Python)

By Mehul Prajapati

Eyeglasses in front of a screen of code, representing the KNN algorithm looking at nearby data points
On this page

K-nearest neighbors (KNN) is a simple machine learning algorithm that predicts a new data point by looking at the k most similar points in the training data. For classification, it takes a majority vote of those neighbours’ classes; for regression, it averages their values. There is no real training step: KNN simply stores the data and does its work at prediction time, which is why it is called a lazy learner. It is easy to understand, a useful baseline, and a great way to learn why feature scaling and model tuning matter.

How KNN works, step by step

  1. Choose a number of neighbours, k (for example 5).
  2. For a new point, calculate its distance to every point in the training data.
  3. Pick the k closest points.
  4. Classification: predict the most common class among them. Regression: predict the average of their values.

Simple example: you want to guess whether a new student will choose the data science or the web development track. You find the 5 past students whose marks in maths, programming and statistics are closest to the new student’s. If 4 of the 5 chose data science, KNN predicts data science.

Distance metrics

Metric Idea When to use
Euclidean Straight-line distance The default; continuous numeric features
Manhattan Sum of absolute differences (grid distance) Many features, or when outliers should count less
Minkowski General form: p=1 gives Manhattan, p=2 gives Euclidean scikit-learn’s default (with p=2)
Cosine Angle between vectors, ignoring their length Text vectors and embeddings
Hamming Number of positions that differ Binary or categorical features

Fun fact: the vector search behind RAG is a nearest-neighbour search too. Vector databases find the k document chunks whose embeddings are closest to your question, usually with fast approximate nearest-neighbour methods.

Why feature scaling is essential for KNN

KNN relies on distances, so a feature measured in large numbers drowns out features measured in small ones. In scikit-learn’s breast cancer dataset, “mean area” ranges from about 143 to 2,501, while “mean smoothness” ranges from about 0.05 to 0.16. Without scaling, the distance is almost entirely decided by area.

A tested example with scikit-learn

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

# 1) Without scaling
raw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
print("Unscaled test accuracy:", round(raw.score(X_test, y_test), 3))

# 2) With scaling inside a pipeline
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
scaled.fit(X_train, y_train)
print("Scaled test accuracy:", round(scaled.score(X_test, y_test), 3))

# 3) Choose k with cross-validation on the training set only
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for k in [1, 3, 5, 7, 9, 15, 25]:
    pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    print(k, round(cross_val_score(pipe, X_train, y_train, cv=cv).mean(), 3))

What we got (scikit-learn 1.9):

  • Without scaling: test accuracy 0.912
  • With StandardScaler: test accuracy 0.956, a clear improvement from one line of preprocessing
k 1 3 5 7 9 15 25
CV accuracy 0.947 0.963 0.963 0.963 0.965 0.960 0.952

The pattern is typical: k=1 is the weakest because it follows single noisy points, very large k starts to blur the classes, and a broad range in the middle performs almost equally well. Putting the scaler inside a pipeline means it is refitted within each cross-validation fold, which avoids data leakage.

How to choose k

  • Small k (1 to 3): very flexible, sensitive to noise, risk of overfitting.
  • Large k: smoother decisions, but can underfit and ignore smaller groups.
  • For two classes, an odd k avoids ties in the vote.
  • Try a range of values with cross-validation, or use GridSearchCV as described in our hyperparameter tuning guide. Also try weights="distance", which lets closer neighbours count more.

Advantages and limitations

Advantages Limitations
Very easy to understand and explain Slow predictions on large datasets: every prediction compares against the stored data
No training time Needs feature scaling
Works for classification and regression Struggles with many features (the curse of dimensionality)
Naturally handles several classes Sensitive to irrelevant features and imbalanced classes

When should you use KNN?

  • Small to medium datasets with a modest number of meaningful numeric features.
  • As a baseline to compare against logistic regression, random forests or Naive Bayes.
  • Simple recommendation and similarity problems (“customers like this one”).
  • Filling missing values with KNNImputer, which uses the same idea.

Frequently asked questions

Is KNN supervised or unsupervised?

KNN classification and regression are supervised: they need labelled data. Do not confuse KNN with K-means, which is an unsupervised clustering algorithm.

Why is KNN called a lazy learner?

Because it does no work during training. It stores the data and postpones all calculation until it has to make a prediction.

What is a good value of k?

There is no universal value. Common starting points are 3, 5 or 7, but always choose k with cross-validation on your own data.

Does KNN work for large datasets?

Plain KNN becomes slow as data grows. Tree-based search structures help for low-dimensional data, and approximate nearest-neighbour libraries are used at large scale, for example in vector databases.

Want to practise KNN and other algorithms on real datasets with guidance? See our Machine Learning course or the complete Data Science course.

A note from Mehul Prajapati

I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in machine learning and want a second opinion on your learning path, I am happy to help.

“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”

Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Machine Learning course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.