KNN (K-Nearest Neighbors, or k nearest neighbors) is a machine learning algorithm based on a simple idea: similar items end up close to each other. To classify something new, it looks at the k closest examples and follows the majority.
Como funciona
KNN is not trained in the traditional sense. It simply stores the labeled examples. When a new item arrives, it does the following:
- Calculates the distance from the new item to all stored examples.
- Selects the k nearest ones.
- For classification, it picks the most common class among them.
- For regression, it takes the average of the neighbors' values.
The value of k changes the result. A very small k makes the model sensitive to noise. A very large k mixes different classes. Usually several values are tested and the best one is chosen.
Because the calculation uses distance, the data needs to be on the same scale. Age and income, for example, should be normalized first.
Exemplo prático
A recipe app wants to suggest the category of a new dish, such as sweet or savory, from ingredients. It has a thousand dishes already labeled. For the new dish, KNN finds the five most similar ones. If four are sweet, the new one will be classified as sweet.
With scikit-learn:
from sklearn.neighbors import KNeighborsClassifier
modelo = KNeighborsClassifier(n_neighbors=5)
modelo.fit(X_treino, y_treino)
previsao = modelo.predict(X_novo)Para que serve
KNN is useful when you want a simple and easy to explain solution:
- Classify items with few data.
- Simple recommendation systems based on similarity.
- A first baseline to compare with more complex models.
- Find similar items, an idea that also appears in similarity search with embeddings.
Limites do KNN
Because it needs to compare with all examples on each prediction, it gets slow on very large datasets. It also struggles when there are many variables, because distance loses meaning in many dimensions. In those cases, reducing dimensions with techniques like PCA helps.
Diferença entre KNN e K-means
The names look similar, but they are different problems. KNN is supervised and uses labeled examples to classify. K-means is unsupervised and groups data without labels.