Predicting a Class with K-Nearest Neighbors (KNN)
Problem Setup
Scenario:Predict whether a website visitor will make a purchase based on how many pages they visited and how long they stayed on the site.
Given:Eight historical visitor records are labeled as Purchased = Yes or No. The target visitor has Pages_Visited = 5 and Time_on_Site_mins = 12, with K = 3.
Task:Use K-Nearest Neighbors to calculate the Euclidean distance from the target visitor to each historical record, identify the 3 closest neighbors, and assign the purchase outcome using their majority class.
Need a quick refresher? Review K-Nearest Neighbors theory
Historical Visitors & Target
The table contains previously observed visitors with known purchase outcomes. Their feature values provide the reference points used to measure how close each visitor is to the target before selecting the nearest neighbors.
| Data Point | Pages_Visited✎ | Time_on_Site_mins✎ | Purchased |
|---|---|---|---|
| P1 | 2 | 5 | No |
| P2 | 3 | 8 | No |
| P3 | 5 | 15 | Yes |
| P4 | 7 | 20 | Yes |
| P5 | 6 | 18 | Yes |
| P6 | 1 | 3 | No |
| P7 | 4 | 10 | No |
| P8 | 8 | 25 | Yes |
| Target | 5 | 12 | ? |
Step-by-Step Solution
Step 1: Calculate Euclidean Distance for each row
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
d =
Step 2: Rank Training Points by Distance
| Rank | Point | Distance | Class |
|---|---|---|---|
| #1 | P7 | 2.236 | No |
| #2 | P3 | 3 | Yes |
| #3 | P2 | 4.472 | No |
| #4 | P5 | 6.083 | Yes |
| #5 | P1 | 7.616 | No |
| #6 | P4 | 8.246 | Yes |
| #7 | P6 | 9.849 | No |
| #8 | P8 | 13.342 | Yes |
Step 3: Pick the top K=3 neighbors & determine majority
Selecting the first 3 rows from our sorted list:
- P7 belongs to class No
- P3 belongs to class Yes
- P2 belongs to class No
Final Answer
Prediction:No
Nearest neighbors:P7 → No, P3 → Yes, P2 → No
Class vote:No: 2 | Yes: 1
This classification reflects the behavior of the selected historical neighbors, not a certainty about whether the visitor will actually make a purchase.
Exam Takeaway
- Check feature scales before calculating distances: Euclidean distance is sensitive to differences in feature ranges. Features with larger numerical ranges can dominate the result, so apply normalization or standardization when appropriate. Use the preprocessing specified in the question.
- Select neighbors using distance, not class labels: Rank all training points by their distance to the query point and select exactly K neighbors. Class labels are used only after the neighbors have been selected. Follow the specified rule when distances are tied.
- Distinguish majority voting from prediction confidence: A class receiving the most votes becomes the KNN prediction, but its vote proportion is not automatically a calibrated probability. Changing K, the distance metric, or feature scaling can change the predicted class.