All lessons in Machine Learning Engineering: Reliable Predictive Models
Nearest Neighbors and Distance Geometry
Diagnose scaling, neighborhood size, and dimensionality in a distance-based baseline.
25 minutes · Free lesson
What you will learn
- Compute Euclidean distances between dispatch records before and after feature scaling and explain why the ranking of neighbors can change.
- Turn a set of k neighbor labels into a late-delivery probability using uniform and inverse-distance weighting, then apply a cost-derived threshold.
- Estimate how the size of a local neighborhood grows with the number of features and recognise when a distance-based baseline is likely to struggle.
A k-nearest-neighbors classifier makes no attempt to learn a formula. When a new parcel is dispatched, it looks up the training records whose features are closest to the new record, reads off how often those records were late, and reports that fraction. For the parcel carrier this is appealing: a dispatcher can be shown the five most similar past dispatches and their outcomes, which is a far more concrete explanation than a logistic coefficient. The catch is that everything hinges on the word closest. Distance is defined by the units and ranges of the features, by the number of features, and by the choice of how many neighbors to consult. This lesson works through each of those decisions with hand-computable fixtures so that you can later judge whether a neighbor-based model deserves a place next to the dummy, logistic, forest, and boosting models in the workbook.
What the prediction contract looks like for neighbors
The prediction contract is unchanged: at dispatch time we have dispatch_load, weather_risk, weekend, and similar features, and we must produce a late probability that is compared against a decision threshold. A neighbor model fulfils that contract with two artefacts, a stored copy of the training rows and a distance function. The neighbor rule stores training data rather than fitting a parametric prediction formula. Preprocessing and an optional search index still require fitting. A brute-force query compares with every stored row; indexing methods can reduce work in suitable settings. For a carrier with millions of historical dispatches that is a real engineering concern, and it is one reason neighbor models are often treated as a diagnostic baseline rather than the deployed model.
That last sentence contains the whole scaling problem. If dispatch_load ranges over hundreds of parcels and weather_risk ranges between 0 and 1, the squared load difference dwarfs the squared weather difference and the model effectively ignores weather, no matter how predictive it is.
Scaling decides which neighbors exist
The usual fix is to standardize each feature using statistics computed on the training rows only: subtract the training mean and divide by the training standard deviation. After this, a one-standard-deviation gap in load counts the same as a one-standard-deviation gap in weather risk. Min-max scaling, which divides by the training range instead, has the same purpose with different sensitivity to extreme rows. Either way the scaler must be fitted on the training split and then applied unchanged to validation, test, and live dispatches; fitting it on the pooled data is a leakage that can move a sample metric in either direction and that the scikit-learn Pipeline object exists to prevent.
Worked example
Raw versus standardized neighbors for one dispatch
- Three stored training dispatches are A with load 120 and weather risk 0.1 (on time), B with load 125 and weather risk 0.9 (late), and C with load 180 and weather risk 0.1 (late). A new dispatch Q has load 122 and weather risk 0.8.
- Raw Euclidean distance from Q to A: load gap 2, weather gap 0.7, so sqrt(4 + 0.49) = sqrt(4.49), about 2.119.
- Raw distance from Q to B: load gap 3, weather gap 0.1, so sqrt(9 + 0.01) = sqrt(9.01), about 3.002.
- Raw distance from Q to C: load gap 58, weather gap 0.7, so sqrt(3364 + 0.49) = sqrt(3364.49), about 58.004.
- With k = 1 the nearest stored dispatch is A and the prediction is on time, even though Q shares B's dangerous weather. The weather gap of 0.7 barely registered against the load units.
- Now suppose the training standard deviation of load is 30 parcels and of weather risk is 0.4. Standardized gaps to A: 2 / 30 = 0.0667 and 0.7 / 0.4 = 1.75, giving sqrt(0.00444 + 3.0625) = sqrt(3.0669), about 1.751.
- Standardized gaps to B: 3 / 30 = 0.1 and 0.1 / 0.4 = 0.25, giving sqrt(0.01 + 0.0625) = sqrt(0.0725), about 0.269.
- Standardized gaps to C: 58 / 30 = 1.9333 and 1.75, giving sqrt(3.7378 + 3.0625) = sqrt(6.8003), about 2.608.
- The nearest neighbor is now B and the prediction flips to late. Nothing about the data changed; only the geometry did. This shows why scaling is part of the model, not an optional cleanup step.
Binary indicators such as weekend need thought as well. A 0/1 feature standardized by its training standard deviation can end up dominating distances when the indicator is rare, because its standard deviation is small. Integer codes with no numeric meaning, such as a depot or route identifier, must never enter a distance unchanged: a difference between code 7 and code 8 is not smaller than a difference between code 7 and code 70. One-hot encode such columns or leave them out of the distance entirely.
From neighbors to a probability and a decision
Once the k nearest stored rows are found, the simplest estimate of the late probability is the fraction of those rows that were late. This is a hard count, and it is exactly what a dispatcher would compute by hand. Scikit-learn's KNeighborsClassifier also supports distance weighting, where each neighbor's vote is multiplied by the inverse of its distance, so a very close match counts more than a borderline one. Under the simplified decision model, with a false-positive cost of 1 and a false-negative cost of 4, and correct probabilities, the cost-minimising threshold is 1 / (1 + 4) = 0.2. A neighbor model must clear that bar using whatever probability it produces, and small k produces coarse probabilities: with k = 5 the only possible values are 0, 0.2, 0.4, 0.6, 0.8, and 1.
Worked example
Uniform and inverse-distance votes for the same five neighbors
- After standardization, the five nearest stored dispatches to a new record have distances 0.2 (late), 0.5 (late), 0.8 (on time), 1.0 (on time), and 1.6 (on time).
- Uniform voting: 2 of 5 neighbors were late, so the estimated probability is 2 / 5 = 0.4.
- Inverse-distance weights: 1 / 0.2 = 5, 1 / 0.5 = 2, 1 / 0.8 = 1.25, 1 / 1.0 = 1, and 1 / 1.6 = 0.625. The weights sum to 5 + 2 + 1.25 + 1 + 0.625 = 9.875.
- The late neighbors carry weight 5 + 2 = 7, so the weighted probability is 7 / 9.875, about 0.709.
- Against the cost threshold of 0.2 both versions flag the dispatch, but the two probabilities differ by about 0.31. If the carrier later reports expected cost or ranks dispatches for a capacity-limited intervention, that gap matters.
- Neither number is automatically calibrated. Whether 0.4 or 0.709 is closer to the true late frequency for records like this one is an empirical question for a calibration plot on held-out data, not something the voting rule settles.
The value of k is a bias-variance dial. With k = 1 and no conflicting duplicate feature vectors, self-neighbor training predictions reproduce their labels, so training accuracy can be a misleading 100 percent and validation behaviour is jumpy. With k equal to the whole training set every prediction collapses to the training late rate, which is just the dummy baseline. The right k is chosen on validation data under the same split design the deployment will face, and then evaluated once on the sealed test set along with whatever threshold was selected.
Why high-dimensional neighborhoods stop being local
Add enough features and the nearest neighbors stop being near. A quick way to feel this is to imagine the rescaled features spread uniformly over a unit cube in d dimensions and ask how wide a cube-shaped neighborhood must be to contain a fraction p of the training rows. Because volume is side length raised to the power d, the required side length is p raised to the power 1 / d. For p = 0.01 and d = 2 the side is 0.01 to the power 0.5 = 0.1, a genuinely local patch. For d = 10 it is 0.01 to the power 0.1, which equals 10 to the power minus 0.2, about 0.631: to gather just one percent of the rows you must span 63 percent of every axis. Such a wide neighborhood no longer provides the same local intuition as in two dimensions. Predictive usefulness still depends on the signal and data geometry. Real features are correlated and not uniform, which softens the effect, but the lesson stands: neighbor models reward compact, informative feature sets and punish wide ones full of noise columns. Feature selection for a neighbor model, like scaling, must be fitted inside the training split.
Three exercises
Exercise
Use the same stored dispatches A (load 120, weather 0.1, on time) and B (load 125, weather 0.9, late) and the query Q (load 122, weather 0.8). This time apply min-max scaling using training ranges: load spans 80 to 200 and weather risk spans 0 to 1. Compute the scaled distances from Q to A and to B and state the k = 1 prediction.
Check your answer
The load range is 200 minus 80 = 120, so load gaps are divided by 120; weather gaps are divided by 1 and are unchanged. Q to A: load gap 2 / 120 = 0.01667, weather gap 0.7, distance sqrt(0.000278 + 0.49) = sqrt(0.490278), about 0.700. Q to B: load gap 3 / 120 = 0.025, weather gap 0.1, distance sqrt(0.000625 + 0.01) = sqrt(0.010625), about 0.103. B is nearest, so the k = 1 prediction is late, agreeing with the standardized result in the worked example and disagreeing with the raw-unit result.
Exercise
The seven nearest stored dispatches to a new record, ordered from closest to farthest, have late labels 0, 0, 0, 1, 1, 0, 0. Using uniform voting, give the late probability for k = 3 and for k = 7, and state whether each clears the cost threshold of 0.2 derived from a false-positive cost of 1 and a false-negative cost of 4. What does the disagreement tell you about how k should be chosen?
Check your answer
For k = 3 the three closest labels are 0, 0, 0, so the probability is 0 / 3 = 0, below 0.2, and the dispatch is not flagged. For k = 7 there are 2 late labels among 7, so the probability is 2 / 7, about 0.286, above 0.2, and the dispatch is flagged. The decision depends entirely on k. That means k cannot be picked by looking at which answer seems right for one record; it must be chosen by comparing validation log loss or validation cost across candidate values, inside the split design, and the chosen k then faces the sealed test set once.
Exercise
Suppose rescaled features are spread uniformly over a unit cube and you want the neighborhood to contain 5 percent of the training rows. Compute the required side length for d = 2 features and for d = 20 features, and interpret the difference.
Check your answer
For d = 2 the side length is 0.05 to the power 0.5, about 0.224, so the neighborhood covers roughly 22 percent of each axis and is reasonably local. For d = 20 the side length is 0.05 to the power 0.05. Using natural logarithms, ln(0.05) is about minus 2.996, divided by 20 gives minus 0.1498, and the exponential is about 0.861. The neighborhood must span about 86 percent of every axis, so the volume argument warns that locality becomes harder to preserve. It does not prove a particular classifier ranking; investigate performance with the actual signal and noise dimensions.
Common mistakes
Fitting the scaler, or any feature selection, on all rows before splitting. The validation score then reflects information from the rows it is supposed to be blind to; the direction of the error is not predictable and the only safe practice is a Pipeline fitted inside each split.
Reporting training accuracy for k = 1, or treating a small-k vote fraction as a calibrated probability. The first can be perfect through self-matching rather than generalization; the second needs a calibration plot on unseen rows before it is trusted at a threshold like 0.2.
Practical investigation
The workbook fits dummy, logistic, forest, and boosting models and selects among them by validation log loss, but it does not include a neighbor model. Download the Machine learning investigation workbook, create a Python 3.12 environment, install requirements.txt, and run python ml_workbook.py --development-only --output results followed by python -m unittest discover -s tests -v to confirm the baseline runs. Then read the source where the candidate models are defined and add a fifth candidate: a Pipeline containing a standard scaler followed by KNeighborsClassifier, with the independent continuous noise_code feature excluded from the distance; its name does not make it a categorical variable. Try a few values of k and both weights='uniform' and weights='distance', judging only by the validation metrics the program writes under the development section of report.json. Resist the temptation to look at the final section until you have settled on a procedure; re-running the script several times checks that your change is reproducible, it does not produce independent statistical evidence. Record whether the neighbor model's validation log loss is competitive and, if it is not, whether removing noise_code and load_proxy changes that. Remember that the synthetic rows are explicitly independent and identically distributed, so nothing here validates how a neighbor model would behave on a real carrier's time-ordered dispatch history.
Further reading
scikit-learn nearest neighbors guide — inspect the uniform and distance weighting options and the tree-based search structures used to avoid comparing against every stored row.
scikit-learn common pitfalls — the section on data leakage during preprocessing explains why scaling must sit inside the Pipeline.
scikit-learn cross-validation guide — use it when choosing k so that the selection is separated from the final evaluation.
Summary
A nearest-neighbor model predicts the late probability of a new dispatch from the labels of the k closest stored dispatches, so its behaviour is governed by the distance geometry. Feature scaling fitted on the training split determines which rows count as close, and raw units can silently discard informative features such as weather risk. The value of k trades jumpiness against collapse toward the training late rate, and small k produces coarse probabilities that are not automatically calibrated against a cost threshold. As the number of features grows, neighborhoods containing a fixed fraction of rows stretch across most of each axis, so neighbor models need compact, informative features. Every one of these choices belongs to validation, with the sealed test used once at the end.
Next action
Add a scaled nearest-neighbor Pipeline to the workbook's candidate models, compare its validation log loss for k in a small range with uniform and distance weighting, and write one paragraph on whether it earns a place among the candidates before you look at any final-test number.