Predicting a Numerical Value with K-Nearest Neighbors (KNN)
Problem Setup
Scenario:Estimate the resale price of a device from its age and battery health using KNN regression.
Given:A labeled dataset of 8 devices with Age_Months and Battery_Health_Percent as input features and Resale_Price_GBP as the numerical target. The target device has Age_Months = 20 and Battery_Health_Percent = 78, with K = 3.
Task:Calculate the Euclidean distance from the target device to each historical device, identify the 3 nearest neighbors, and average their resale prices to obtain the predicted value.
Need a quick refresher? Review K-Nearest Neighbors theory
Historical Devices & Resale Prices
Each row represents a previously sold device with its age, battery condition, and observed resale price. These examples provide the reference points for finding devices most similar to the target and estimating its resale value.
| Data Point | Age_Months✎ | Battery_Health_Percent✎ | Resale_Price_GBP |
|---|---|---|---|
| P1 | 6 | 95 | 850 |
| P2 | 12 | 88 | 720 |
| P3 | 18 | 80 | 600 |
| P4 | 24 | 72 | 500 |
| P5 | 30 | 65 | 420 |
| P6 | 8 | 92 | 800 |
| P7 | 15 | 85 | 650 |
| P8 | 36 | 55 | 320 |
| Target | 20 | 78 | ? |
Step-by-Step Solution
Step 1: Calculate Euclidean Distance for each row
P1 =
P1 =
P1 =
P2 =
P2 =
P2 =
P3 =
P3 =
P3 =
P4 =
P4 =
P4 =
P5 =
P5 =
P5 =
P6 =
P6 =
P6 =
P7 =
P7 =
P7 =
P8 =
P8 =
P8 =
Step 2: Rank Training Points by Distance
| Rank | Point | Distance | Target Value |
|---|---|---|---|
| #1 | P3 | 2.828 | 600 |
| #2 | P4 | 7.211 | 500 |
| #3 | P7 | 8.602 | 650 |
| #4 | P2 | 12.806 | 720 |
| #5 | P5 | 16.401 | 420 |
| #6 | P6 | 18.439 | 800 |
| #7 | P1 | 22.023 | 850 |
| #8 | P8 | 28.018 | 320 |
Step 3: Average the 3 Nearest Target Values
Prediction = (600 + 500 + 650) / 3
Prediction = 1750 / 3
Prediction = 583.333
Final Answer
Nearest neighbors:P3 (£600), P4 (£500), P7 (£650)
Predicted resale price:£583.33
The estimate reflects the average resale price of similar historical devices. It is a prediction based on the selected neighbors, not a guaranteed selling price.
Exam Takeaway
- Keep input features separate from target values: Calculate distances using the input features only. The target values are used after selecting the nearest neighbors to calculate the regression prediction.
- Check feature scales before calculating distances: Euclidean distance is sensitive to numerical ranges, so features with larger scales can dominate neighbor selection. If scaling is required, apply the same transformation to both training points and the query point.
- Understand how K affects the prediction: A smaller K makes predictions more sensitive to individual nearby observations, while a larger K averages more target values and generally produces a smoother estimate. Neither choice guarantees the most accurate prediction.