# kNN

{% hint style="info" %}
*Sources:*

* [*KNN (Towards Data Science)*](https://towardsdatascience.com/knn-k-nearest-neighbors-1-a4707b24bd1d)
* [*KNN Classification using Scikit-learn (Avinash Navlani)*](https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn)
  {% endhint %}

## **How it works**

{% hint style="danger" %}
Is an [**instance-based algorithm**](https://jgoodman8.gitbook.io/iron-data-science-notebook/frequent-questions/instance-based-vs-model-based-learning#instance-based-learning)**.** So, there is **not training step**. Classification is directly inferred!
{% endhint %}

For every unlabeled instance (the ones to be classified):

1. It measures the **distance to every labeled sample**.
2. It **sorts** the distances incrementally.
3. It selects the **closets&#x20;*****k*****&#x20;instances**.
4. It **assigns the most frequent class** on the selected *k* instances.

![Source: DataCamp](https://569842953-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LmjpNbCRLUyGiAxD8kn%2F-LrEv4l-pJ9q7MwcIaoY%2F-LrEv5gAYmEj7WjuAn-S%2Fimage.png?alt=media\&token=b0ae4186-1508-48da-bd9e-979000a5d37d)
