Beginner Topic 11 of 51 AI & Machine Learning
k-Nearest Neighbors
Classifying by majority vote of the closest examples.
How it works
The k-nearest neighbors algorithm predicts for a new point by finding the k closest training examples under a distance metric, usually Euclidean, and taking the majority class or the average value. It is a lazy, instance-based method: there is no training phase and the model is the data itself. The choice of k balances noise sensitivity against smoothing, and distance weighting gives closer neighbors more influence.
Step-by-step walkthrough
- Store all training examples.
- For a new point compute distances to all of them.
- Pick the k closest, say 3.
- Take a majority vote among their labels.
- No training is needed, but prediction is slow on large data.
Where it is used
Recommendation systems, anomaly detection, image retrieval, simple classifiers and imputation of missing values use k-NN, as do vector similarity searches.
Common pitfall
Prediction is slow for large datasets without indexes such as k-d trees or approximate nearest neighbor methods, and memory use is high. Performance degrades in high dimensions as distances become less meaningful, the curse of dimensionality. Unscaled features dominate distance, and irrelevant features add noise. Standardize features, choose k with cross-validation and consider dimensionality reduction.
Where it fits in the course
k-Nearest Neighbors is topic 11 of 51 in AI & Machine Learning, rated Beginner. It follows Decision Trees. The next topic is k-Means Clustering.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the AI & Machine Learning quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the AI & Machine Learning quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is k-Nearest Neighbors?
Where do people use k-Nearest Neighbors?
What is the most common mistake with k-Nearest Neighbors?
What should I learn before this topic?
How can I practice it?
Is k-Nearest Neighbors hard to learn?
How long does it take to learn k-Nearest Neighbors?
Which topics are related to k-Nearest Neighbors?
What should I study after k-Nearest Neighbors?
Related topics
- Decision Trees (AI & Machine Learning)
- k-Means Clustering (AI & Machine Learning)
- Logistic Regression (AI & Machine Learning)
- Overfitting and Underfitting (AI & Machine Learning)