topskill.dev
CoursesTracks
All courses/Machine Learning FundamentalsNearest neighbors
Supervised prediction algorithms
4 / 10
← Machine Learning Fundamentals
○What machine learning learns○Features and labels○Training and inference○Regression or classification○The machine learning process○Data quality and coverage○Representing data✦Module Quiz
○Linear regression○Try a tiny linear model○Logistic regression●Nearest neighbors○Decision trees○Random forests○Boosting○Naive Bayes○Support vector machines✦Module Quiz
○Clustering○K-means○Choosing and interpreting clusters○Principal component analysis○Neural networks and deep learning○Self-supervised learning○Transfer learning○Reinforcement learning✦Module Quiz
○Generalization and overfitting○Holding out evaluation data○Data leakage○Baselines○Bias and variance intuition○Reading learning curves✦Module Quiz
○Prediction errors and residuals○Measuring regression error○Squared error and large misses○The confusion matrix○Precision and recall○Try a held-out classifier✦Module Quiz
○Bias and limits○Monitoring and drift○Comparing models for a decision✦Module Quiz
Supervised prediction algorithms

Nearest neighbors

A k-nearest neighbors model, often shortened to kNN, finds the kkk closest training examples to a new input. Here kkk is the number of neighbors considered. For classification, a simple version takes their majority category; for regression, it averages their target values.

With distance as the only feature, two trips are close when their kilometer values are close:

d=∣x−a∣d=|x-a|d=∣x−a∣

Here ddd is their distance in feature space, xxx is the new trip's kilometer value, and aaa is a stored trip's kilometer value. The vertical bars mean absolute value: ignore the sign. A 4-kilometer trip is ∣4−3∣=1|4-3|=1∣4−3∣=1 kilometer away from a stored 3-kilometer trip on this feature.

If its three nearest stored trips took 17, 20, and 23 minutes, their average prediction is (17+20+23)/3=20(17+20+23)/3=20(17+20+23)/3=20 minutes. Those are invented neighbor times.

Small kkk can make predictions sensitive to one unusual example. Larger kkk smooths predictions but may include cases that are less relevant. With several features, scaling and the definition of distance matter. Storing examples is simple; searching a large collection at prediction time can be expensive.

The stored training features and targets are part of the fitted system. A new input has no known target when its neighbors are selected. Choosing neighbors by looking at its true target would defeat the prediction task. A distance rule also needs a policy for ties; the simple majority example assumes no tie.

Check your understanding

For three equally weighted neighbors labeled late, on time, and late, what is the predicted category?

Answer: Late, because two of the three neighbors have that label.

Fact 1
1 / 1
FACT 1

Late, because two of the three neighbors have that label.