How It Works ?
K-Nearest Neighbors is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection.
The K-Nearest Neighbors (KNN) algorithm is a simple, easy-to-implement supervised machine learning algorithm that can be used to solve both classification and regression problems.
The KNN algorithm assumes that similar things exist in close proximity. In other words, similar things are near to each other. KNN captures the idea of similarity (sometimes called distance, proximity, or closeness) with some mathematics we might have learned in our childhood— calculating the distance between points on a graph. There are other ways of calculating distance, and one way might be preferable depending on the problem we are solving. However, the straight-line distance (also called the Euclidean distance) is a popular and familiar choice.
It is widely disposable in real-life scenarios since it is non-parametric, meaning, it does not make any underlying assumptions about the distribution of data (as opposed to other algorithms such as GMM, which assume a Gaussian distribution of the given data).
This article demonstrates an illustration of K-nearest neighbours on a sample random data using sklearn library.
We’ve been given a random data set with one feature as the target classes. We’ll try to use KNN to create a model that directly predicts a class for a new data point based off of the features.
Let’s first visualize our data with Multiple Features.
Get the data:
Set index_col=0 to use the first column as the index.
Standardize the Variables:
Because the KNN classifier predicts the class of a given test observation by identifying the observations that are nearest to it, the scale of the variables matters. Any variables that are on a large scale will have a much larger effect on the distance between the observations, and hence on the KNN classifier than variables that are on a small scale.
Train Test Split Data and Use KNN model from sklearn library:
[[133 16] [ 15 136]] precision recall f1-score support 0 0.90 0.89 0.90 149 1 0.89 0.90 0.90 151 accuracy 0.90 300 macro avg 0.90 0.90 0.90 300 weighted avg 0.90 0.90 0.90 300
Choosing a K Value:
Let’s go ahead and use the elbow method to pick a good K Value
Here, we can see that that roughly after K>15 the error rate just tends to hover between 0.07-0.08 Let’s retrain the model with that and check the classification report.
WITH K=1 [[133 16] [ 15 136]] precision recall f1-score support 0 0.90 0.89 0.90 149 1 0.89 0.90 0.90 151 accuracy 0.90 300 macro avg 0.90 0.90 0.90 300 weighted avg 0.90 0.90 0.90 300 WITH K=15 [[133 16] [ 6 145]] precision recall f1-score support 0 0.96 0.89 0.92 149 1 0.90 0.96 0.93 151 accuracy 0.93 300 macro avg 0.93 0.93 0.93 300 weighted avg 0.93 0.93 0.93 300
Great! We were able to squeeze some more performance out of our model by tuning to a better K value.
- r-Nearest neighbors
- Implementation of K Nearest Neighbors
- k-nearest neighbor algorithm in Python
- Python | Fetch Nearest Hospital locations using GoogleMaps API
- K-Nearest Neighbours
- MySQL-Connector-Python module in Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to a Python Script
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.