Understand the idea
k-NN is prediction by analogy: to guess the outcome for a new observation, find the k rows in your data that look most similar to it (measured by straight-line distance across all the predictors) and let those neighbors decide the answer: majority vote for a category, simple average for a number. There is no equation being fit here at all; the 'model' is just the stored data plus a rule for finding neighbors and asking them.
Because distance is computed by adding up squared differences across predictors, a predictor measured in big units (grams) can completely swamp one measured in small units (millimeters) unless every predictor is first rescaled onto a common footing (standardized). Skipping this step effectively means only the largest-scale predictor gets a vote.
The number of neighbors, k, is the single dial that controls how flexible the model is. k=1 is maximally flexible: it follows every quirk of the training data closely, which sounds good but actually means it has memorized noise and will often guess badly on new data. A large k is the opposite: very smooth, but potentially blind to real local structure. The right k sits in between, and training accuracy can NEVER find it (training accuracy always looks best at k=1); only checking performance on data the model has not seen can reveal the sweet spot.
Used for classes, k-nearest neighbors is nearest neighbor classification: a new row gets the most common class among the k most similar rows. k-nearest neighbors is called lazy learning because it does no fitting up front; all the work happens when a new row arrives. The curse of dimensionality means that with many columns every row ends up far from every other, so the 'nearest' neighbors stop being meaningfully near.
Practitioner explanation
KernelStats standardizes predictors INSIDE each cross-validation fold (not once, upfront, on the whole dataset) so no information about the held-out rows leaks into the scaler used to fit and predict on them, a genuine, easy-to-miss form of data leakage that this implementation specifically avoids. Distance weighting (weights='distance') gives closer neighbors more influence (1/d); with distance weights, a neighbor at distance exactly 0 (a duplicate row, or a constant-predictor combination) would need weight 1/0, so KernelStats rejects that specific combination outright rather than silently producing an infinite or NaN weight.
When auto-select k is on (the default), KernelStats searches k = 1, 3, ..., 25 by cross-validation and reports the k-vs-score curve, breaking ties toward the LARGER, smoother k. Critically, it does NOT report the winning search score as the model's honest performance estimate: because k was CHOSEN to maximize that score across 13 candidate values, the winning score is itself optimistic (the maximum of 13 noisy estimates sits above the truth, and even pure noise would produce a best-of-13 result that beats chance comfortably). The card instead reports a NESTED cross-validation estimate: inside each outer fold, k is re-selected from scratch on that fold's training data alone, and the model is scored on the truly held-out rows, with the raw search maximum still shown separately as selection_score, explicitly flagged as a selection criterion rather than a performance estimate. With a FIXED (non-auto) k, there is nothing to select, so the ordinary (non-nested) cross-validated score is already unbiased and is used directly.
k-NN is 'lazy learning': there is no fitted equation to inspect, and prediction cost grows with the size of the stored dataset because every prediction searches it. The curse of dimensionality is stated as a real, practical limitation: with roughly 10 or more predictors, the notion of 'nearest' stops being meaningful (points become almost equally far apart in high-dimensional space), and the product recommends preferring a model that learns structure (regression, trees) or reducing dimensions first (PCA) once predictor count grows past a handful.
When to use it
Consider it when
Predicting a category or number from numeric predictors when the relationship is expected to be local and possibly highly non-linear, and an interpretable equation is not needed. Works best with a handful of predictors and plenty of rows.
Use caution when
More than about 10 predictors (the curse of dimensionality makes 'nearest' stop being meaningful), a need for an interpretable coefficient or equation (k-NN has none to offer), unscaled predictors left unstandardized, or very large datasets where per-prediction search cost becomes a practical bottleneck.
Formulas and symbols
k-NN regression prediction
N_k(x) the set of k nearest neighbors to x by Euclidean distance in predictor space.
Euclidean distance
The straight-line distance between two rows across p standardized predictors.
Nested cross-validation performance (auto-k)
The nested estimate re-selects k from scratch inside each outer fold's training data; the raw search maximum (selection_score) is systematically optimistic because k was chosen to maximize it.
Assumptions and checks
- k-NN classifies or predicts by Euclidean distance to the nearest neighbors; predictors on very different scales let the largest-scale variable dominate that distance, so unstandardized inputs make the model reflect scale rather than genuine similarity.
In KernelStats: Checked directly: the card reports whether predictors were standardized, or (if not) the ratio between the largest and smallest predictor spread, flagging a ratio above 10 as a warning.
- In higher dimensions, points become nearly equidistant from each other (the curse of dimensionality), so the 'nearest' neighbors stop being meaningfully closer than the rest of the data and predictions degrade.
In KernelStats: Checked directly: the card reports rows per predictor dimension and flags it as a warning when there are 10 or more predictors with fewer than 10 rows per dimension.
- With a severely imbalanced classification target, majority-class neighbors can dominate the vote for almost every query point regardless of the true local pattern, understating how useful the model is for the minority class.
In KernelStats: Checked directly for classification: the card reports the smallest class's share of rows and flags it below 10%.
Alternatives
- Logistic Regression. You need an interpretable coefficient table with effect sizes, rather than a model with no fitted equation to inspect.
- Decision Tree (CART). The number of predictors is too large for distance-based neighbors to stay meaningful, but you still want an inspectable model.
- Principal Component Analysis. Dimensionality is too high for k-NN to work well and you want to reduce it before attempting distance-based prediction.
Worked example
Scenario
Classifying penguin species from bill length and flipper length, with auto-select k searching 1 through 25 via 5-fold cross-validation.
Result
The search's best score occurs at k = 5 (selection_score = 96.2% accuracy); the nested cross-validation estimate for the whole procedure is 95.9%, with the outer folds choosing k = 13, 7, 5, 5 and 3.
Interpretation
The gap between 96.2% and 95.9% is the optimism introduced by searching 13 candidate k values and reporting the winner; it is small here because the curve is flat near its peak, but 95.9% is the number that honestly reflects how the whole k-selection procedure would perform on new penguins. The spread of k across outer folds is a reminder that the 'best k' itself is uncertain.
Dataset: penguins.csv
Common misconceptions
Misconception
The best cross-validated score found while searching for the right k (auto-select) is the model's honest accuracy.
Correction
That score is the MAXIMUM across many candidate k values (1, 3, ..., 25), and choosing k specifically to maximize it means the winning score is itself optimistic; even pure noise would produce an inflated best-of-13 result that beats chance. The honest performance estimate requires NESTED cross-validation, re-selecting k from scratch inside each outer fold, which is what this card reports as its headline rather than the raw search maximum.
Misconception
k-NN with k=1 is the best choice because it achieves perfect (zero-error) training accuracy.
Correction
At k=1, every training point is trivially its own nearest neighbor, so training error is zero BY CONSTRUCTION regardless of whether the model is any good; this is the textbook overfitting trap, not evidence of quality. Training accuracy can never reveal the right k because it always favors the smallest one; only cross-validated performance on unseen data can locate the actual bias-variance sweet spot.
References
- Nearest neighbor pattern classification, Cover, T. and Hart, P. (1967), IEEE Transactions on Information Theory, 13(1), 21-27.
- An Introduction to Statistical Learning with Applications in R (2nd ed.), Chapters 2-4, James, G., Witten, D., Hastie, T. and Tibshirani, R. (2021).
