Step 1: Calculate the Distance
First, it takes a new, unseen data point and calculates the distance between that point and every single point in the training dataset, using a chosen distance metric like Euclidean or Manhattan distance.
For two data points with multiple features, KNN commonly uses Euclidean distance.
Euclidean Distance = √[(X₁ − Y₁)² + (X₂ − Y₂)² + ... + (Xₙ − Yₙ)²]
For example, consider two points:
Point A = (5, 7)
Point B = (2, 3)
Distance = √[(5 − 2)² + (7 − 3)²]
Distance = √[9 + 16] = √25 = 5
Step 2: Rank the Data Points
Once the distances are calculated, KNN sorts the data points from the smallest distance to the largest distance.
For example:
Data Point | Distance | Class |
A | 1.2 | Pass |
B | 1.8 | Pass |
C | 2.1 | Fail |
D | 3.4 | Fail |
E | 4.2 | Pass |
If K = 3, the algorithm selects A, B, and C because they are the three closest points.
Step 3: Make a Classification Prediction
For classification, KNN uses majority voting to determine the predicted class.
Predicted Class = Mode(Class of K Nearest Neighbours)
In the example, the three nearest neighbours are:
Since Pass appears twice, the new data point is classified as Pass.
Step 4: Make a Regression Prediction
For regression, KNN generally calculates the average target value of the K nearest neighbours.
Predicted Value = (y₁ + y₂ + ... + yₖ) / K
For example, if the three nearest properties have prices of ₹50 lakh, ₹55 lakh, and ₹60 lakh:
Predicted Price = (50 + 55 + 60) / 3
Predicted Price = ₹55 lakh
Therefore, KNN predicts the new property's price as ₹55 lakh.
Step 5: Complete the Prediction Process
The overall working of the K nearest neighbor algorithm can be summarised as:
New Data Point
Calculate Distance
Rank Data Points
Select K Neighbours
Vote/Average
Final Prediction
After exploring the working of the K Nearest Neighbors algorithm, it’s now time to see how the K Nearest Neighbor algorithm can be implemented in Python.
Also Read: Gradient Boosting Algorithm in Machine Learning: How It Works, and Practical Examples
How to Implement KNN in Python
Let’s see the complete k nearest neighbor algorithm python example using scikit-learn, with separate practical examples for KNN classification and KNN regression.
Import Required Libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
confusion_matrix, mean_squared_error, r2_score
)
Load and Prepare the Dataset
KNN classification example:
np.random.seed(42)
n = 200
class0 = np.random.normal(loc=[3, 3], scale=1.5, size=(n // 2, 2))
class1 = np.random.normal(loc=[6, 6], scale=1.5, size=(n // 2, 2))
X = np.vstack([class0, class1])
y = np.array([0] (n // 2) + [1] (n // 2))
df = pd.DataFrame(X, columns=["Feature1", "Feature2"])
df["Label"] = y
print(df.head())
This creates two overlapping clusters of 100 points each, a simple k nearest neighbor algorithm example used to demonstrate binary classification.
Split the Data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
Scale the Features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
As covered earlier, scaling is essential for KNN specifically, since the algorithm's predictions are based entirely on distance calculations that can be distorted by features on different numeric scales.
Train the KNN Model
clf = KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train_scaled, y_train)
Setting n_neighbors=5 means the model will look at the 5 nearest training points whenever it makes a prediction, consistent with the value of K covered earlier in this guide.
Make Predictions
y_pred = clf.predict(X_test_scaled)
Evaluate the Model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
print("F1-score:", f1_score(y_test, y_pred))
print("Confusion matrix:\n", confusion_matrix(y_test, y_pred))
Running this classification example produces an accuracy of roughly 0.975, a precision of 1.0, a recall of roughly 0.95, and an F1-score of roughly 0.97, showing the model correctly separates the two clusters with only a single misclassification in the test set.
KNN regression example, predicting house price from size, bedrooms, and age:
np.random.seed(7)
size = np.round(np.random.uniform(500, 3500, n))
bedrooms = np.random.randint(1, 5, n)
age = np.round(np.random.uniform(0, 30, n))
price = 20000 + size 120 + bedrooms 8000 - age * 500 + np.random.normal(0, 15000, n)
df_house = pd.DataFrame({"Size": size, "Bedrooms": bedrooms, "Age": age, "Price": price})
X_reg = df_house[["Size", "Bedrooms", "Age"]]
y_reg = df_house["Price"]
X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
X_reg, y_reg, test_size=0.2, random_state=42
)
scaler_r = StandardScaler()
X_train_r_scaled = scaler_r.fit_transform(X_train_r)
X_test_r_scaled = scaler_r.transform(X_test_r)
reg = KNeighborsRegressor(n_neighbors=5)
reg.fit(X_train_r_scaled, y_train_r)
y_pred_r = reg.predict(X_test_r_scaled)
mse = mean_squared_error(y_test_r, y_pred_r)
rmse = np.sqrt(mse)
r2 = r2_score(y_test_r, y_pred_r)
print("RMSE:", rmse)
print("R2 score:", r2)
On this regression example, the model achieves an R² score of roughly 0.93 and an RMSE of roughly 29,600, meaning it explains about 93 percent of the variance in house price and its predictions are typically off by around that RMSE amount, a solid result for a simple, untuned KNN regressor.
Also Read: Support Vector Machine (SVM) in Machine Learning: Algorithm, Types, Kernels, and Examples
Real world applications of K Nearest Neighbors Algorithm tells how it is applied in various use cases, and helps to understand the algorithm more clearly. Let’s explore some of the applications of k nearest neighbor algorithm in machine learning.
Applications of K Nearest Neighbors Algorithm in Real-World
The K nearest neighbors algorithm can be applied to several classification and regression problems where similarity between observations is useful.
Some key applications of K Nearest Neighbors Algorithm are:
Industry | Prediction Problem | Example Application |
Healthcare | Classification | Classifying patients based on similar clinical characteristics |
Finance | Classification | Identifying customers with similar credit profiles |
E-commerce | Recommendation | Finding products or customers with similar behaviour |
Marketing | Customer segmentation | Grouping customers based on similar characteristics |
Education | Classification | Predicting student outcomes based on similar learning patterns |
Real Estate | Regression | Estimating property prices using similar properties |
Retail | Recommendation | Recommending products based on similar customer preferences |
Image Recognition | Classification | Classifying images based on similar feature patterns |
Now that we have explored the applications of the K Nearest Neighbors Algorithm, let’s take a look at the k nearest neighbor algorithm advantages and disadvantages to understand its strengths and limitations.
Advantages and Disadvantages of K Nearest Neighbors Algorithm
Like every machine learning technique, KNN has strengths and weaknesses. Understanding these can help you to determine whether it is suitable for your particular problem or not.
Advantages of K Nearest Neighbors Algorithm
Simple to understand: The algorithm follows an intuitive similarity-based approach.
Easy to implement: K Nearest Neighbors Algorithm can be implemented with relatively little code using machine learning libraries.
No complex training process: It does not require learning a complex set of model parameters during training.
Works for classification and regression: KNN can solve both categorical and numerical prediction problems.
Flexible decision boundaries: KNN can capture nonlinear relationships because predictions are based on local observations.
Disadvantages of K Nearest Neighbors Algorithm
Prediction can be computationally expensive: The algorithm may need to calculate distances to many training observations.
Sensitive to feature scaling: Features with larger numerical ranges can dominate distance calculations.
Sensitive to the choice of K: A poorly selected K can lead to underfitting or overfitting.
Affected by irrelevant features: Unimportant variables can distort distance calculations.
Performance can decline with high-dimensional data: As the number of features increases, identifying meaningful nearest neighbours can become more difficult.
Conclusion
So far, you have learned that the K Nearest Neighbors algorithm remains a valuable tool in machine learning because it closely mirrors human intuition. When predicting something about a new observation, it looks at what similar observations can already tell us.
Understanding K, distance metrics, feature scaling, and the lazy learning approach behind KNN gives a strong foundation for using it effectively, whether for classification, regression, or as a reliable baseline before moving on to more complex algorithms.