Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 64

Understanding K-Nearest Neighbors (KNN)

Recommended resources

Introduction

In our last lesson, you successfully trained and evaluated a logistic regression model. You learned how that model works by finding an optimal mathematical function—a decision boundary—to separate different classes. This is a common approach in machine learning: the model "learns" a general rule from the data during a distinct training phase.

Today, we explore a fundamentally different and remarkably intuitive classification algorithm: k-Nearest Neighbors (KNN). Your learning outcome for this lesson is to describe the k-nearest neighbors (KNN) algorithm and its distance-based logic.

Unlike logistic regression, KNN is a "lazy learner." It doesn't learn a discriminative function from the training data. Instead, it memorizes the entire training dataset and makes predictions based on the principle of similarity, or "nearness." This lesson will lay the theoretical groundwork for this powerful and simple algorithm, aligning with your preference for a theory-first approach before moving on to practical implementation.


The Core Idea: You Are Known by the Company You Keep

The foundational assumption of KNN is simple: similar things exist in close proximity. If you want to classify a new, unknown data point, you can look at its closest neighbors in the dataset whose classes you already know. The new point is then assigned the class that is most common among those neighbors.

To get a clear visual intuition for this process, let's watch a segment from StatQuest, a channel known for its excellent explanations.

StatQuest: K-nearest neighbors, Clearly Explained

The video 'StatQuest: K-nearest neighbors, Clearly Explained' provides a fantastic visual introduction to the core logic of the algorithm.

Please watch from 00:21 to 02:44. Focus on how the classification of the new, unknown data point changes based on: Its position relative to the known data points. The value of 'k' (the number of neighbors considered).

The process you just saw can be broken down into a few logical steps. This image provides a great summary of the entire workflow.

K-Nearest Neighbors (KNN) Algorithm Explained Step-by-Step
This diagram illustrates the four key steps of the KNN algorithm. 1) Start with a dataset of labeled points and a new, unlabeled point. 2) Calculate the distance from the new point to all other points. 3) Identify the 'k' nearest neighbors (here, k=3). 4) The new point is assigned the class that has the majority vote among its neighbors.

The "Distance-Based Logic": Quantifying Nearness

The central mechanism of KNN is its distance-based logic. To find the "nearest" neighbors, the algorithm must mathematically calculate the distance between the new data point and every single point in the training set.

The most common way to measure this distance in a multi-dimensional space is the Euclidean distance. Given your BTech background, you'll recognize this as a generalization of the Pythagorean theorem. For two points, and , in a 2D plane, the Euclidean distance is:

This formula extends naturally to any number of dimensions (features).

Let's see a concrete example of this calculation in action.

KNN Algorithm In Machine Learning | KNN Algorithm Using Python | K Nearest Neighbor | Simplilearn

The Simplilearn video 'KNN Algorithm In Machine Learning' walks through a practical calculation of Euclidean distance.

Watch from 06:36 to 09:18. Follow the step-by-step calculation to classify a new data point based on height and weight. Notice how the algorithm: Calculates the Euclidean distance from the new point to several existing points. Identifies the nearest neighbors based on these calculated distances. Makes a final prediction using a majority vote from those neighbors.

Other Distance Metrics

While Euclidean distance is standard, it's not the only option. The choice of distance metric can be important depending on your data. For a more formal look at the mathematics, the following reading provides a concise summary.

The Math Behind K-Nearest Neighbors

The article 'The Math Behind K-Nearest Neighbors' from Towards Data Science clearly lays out the formulas for the most common distance metrics used in KNN.

Read the section 2.1: The Mathematics Behind KNN. Focus on understanding the definitions and formulas for: Euclidean Distance: The straight-line distance. Manhattan Distance: The 'city block' distance, useful when movement is constrained to a grid. Minkowski Distance: A generalized metric where Euclidean and Manhattan are special cases.

Understanding these different metrics is key. The choice of distance function is, in itself, a way of defining what "similarity" means for your specific problem.


The KNN Algorithm: A Formal Summary

Let's consolidate what we've learned into a formal, step-by-step description of the KNN algorithm for classification:

  1. Choose a value for 'k': Select the number of nearest neighbors to consider. This is a hyperparameter you must set.
  2. Calculate Distances: For a new, unclassified data point, calculate its distance to every point in the training dataset using a chosen distance metric (e.g., Euclidean).
  3. Identify Nearest Neighbors: Sort the calculated distances in ascending order and select the top 'k' data points from the training set—these are the 'k-nearest neighbors'.
  4. Vote for the Class: Tally the classes of the 'k' selected neighbors. The new data point is assigned the class that has the most votes (the majority class).

This entire process is performed at prediction time, which is why KNN is called a "lazy" algorithm—all the heavy computation is deferred until a prediction is requested.


The Critical Role of 'K'

As you might have guessed, the choice of k has a significant impact on the model's predictions. It's the primary lever you have to control the model's behavior and represents a classic bias-variance tradeoff, a concept we discussed in Module 7.

  • A small k (e.g., k=1): The model is very flexible and highly sensitive to noise or outliers in the data. The decision boundary will be very irregular. This leads to low bias but high variance and a risk of overfitting.
  • A large k: The model becomes more robust to noise by considering a wider neighborhood. The decision boundary becomes much smoother. This leads to high bias (it might oversimplify the true pattern) but low variance. If k is too large, it can lead to underfitting.

StatQuest: K-nearest neighbors, Clearly Explained

Let's revisit the StatQuest video to solidify our understanding of how to choose a value for 'k'.

Watch the segment from 04:08 to 05:05. Josh Starmer discusses the practical trade-offs when picking 'k' and a common method for evaluating which 'k' is best.

A common heuristic is to choose an odd value for k in binary classification problems to avoid ties in the voting process. The optimal k is usually found through experimentation, a process we will cover in future lessons.


Advantages and Disadvantages of KNN

To make intelligent decisions like the "Tony Stark" archetype you aspire to, you must understand the strengths and weaknesses of your tools. KNN is no exception.

K-Nearest Neighbor(KNN) Algorithm - GeeksforGeeks

The GeeksforGeeks article on KNN provides a concise list of its main advantages and disadvantages. This will help you understand when KNN might be a suitable choice for a problem.

Please read the two short sections titled 'Advantages of KNN' and 'Disadvantages of KNN'.

In summary:

  • Strengths: Its simplicity and intuitiveness are major assets. It requires no explicit training phase and can be easily adapted for both classification and regression (by averaging the values of the neighbors instead of voting).
  • Weaknesses: It can be computationally slow for large datasets because it must compute distances to all training points for each prediction. It's also sensitive to the scale of the data and can perform poorly with high-dimensional data (the "curse of dimensionality").

Conclusion

In this lesson, you have explored the theoretical foundations of the k-Nearest Neighbors algorithm. You've moved beyond the function-fitting paradigm of logistic regression to an instance-based approach grounded in the intuitive concept of similarity.

Key Takeaways:

  • KNN is a supervised, non-parametric, and lazy-learning algorithm.
  • Its core principle is to classify new data based on the majority class of its 'k' nearest neighbors.
  • The "nearness" of neighbors is quantified using distance metrics, with Euclidean distance being the most common.
  • The choice of the hyperparameter 'k' is critical and involves a bias-variance tradeoff. A small k can be noisy (high variance), while a large k can be overly smoothed (high bias).
  • KNN is simple to understand but can be computationally expensive at prediction time.

Preview of the Next Lesson:
With this theoretical foundation firmly in place, you are now ready to put it into practice. In the next lesson, you will implement the KNN algorithm for classification using scikit-learn. You will apply the familiar scikit-learn workflow to a real dataset and see firsthand how this distance-based logic translates into Python code.