- Introduced by
- Cover, T. & Hart, P. (KNN); XAI extensions by various authors
- Year
- 1967 (KNN); 2010s (explainability extensions)
- Type
- Instance-based learning with explainability layer
- Family
- Machine learning
What does it do?
Explainable K-Nearest Neighbors (XKNN) is a family of K-Nearest Neighbors (KNN) classifiers and regressors that add explanation outputs to each prediction: the retrieved neighbors, their distances, and, in some variants, feature-level contributions and counterfactual neighbors.
Because each prediction is tied to stored training cases, a human reviewer can check the explanation against those cases. XKNN does not denote one standardised algorithm, so the exact explanation outputs depend on the implementation.
The intuition behind the method
KNN predicts from the closest training examples, so the neighbors behind a prediction can be shown to a user directly. Explainable variants make this explicit by reporting each neighbor's distance and influence weight, attributing parts of the distance to individual features, and identifying nearby neighbors that carry a different label from the prediction. The prediction rule itself is unchanged; the explanation reports on the neighborhood that the rule already uses.
History
The nearest neighbor decision rule is associated with Cover and Hart (1967). Their paper analyses the nearest-neighbor rule independently of the underlying distribution and, in a large-sample analysis for suitably smooth distributions, bounds its error probability relative to the Bayes error. For any number of categories, the abstract states that this error is bounded above by twice the Bayes error. The general k-NN rule is commonly traced to the same line of work, but the abstract addresses only the nearest-neighbor case. Papernot and McDaniel (2018) is an arXiv preprint whose title, Deep k-Nearest Neighbors: Towards Confident, Interpretable and Robust Deep Learning, indicates interpretability aims. No abstract for that work was available for this page, so its content is not described here, and it is not treated as the origin of the XKNN explanation outputs. The origins of the explanation-oriented variants are not covered by verified sources on this page.
When to use it
Choose XKNN when a prediction must be justified by reference to concrete training cases and the data has a meaningful distance structure, for example in clinical, credit or legal settings where a reviewer needs to inspect the cases behind an outcome. It is suited to tabular data of moderate size, where retrieving neighbors remains affordable. Do not use it when the features are high-dimensional and have not been reduced or given a suitable metric, when the dataset is so large that exact retrieval is too costly, or when only overall model behaviour matters rather than the justification of individual predictions. Storing raw training records inside the model should also be weighed against privacy requirements.
Limitations and considerations
- Brute-force retrieval costs O(n·d) per query, so exact search becomes expensive as the training set grows; approximate search structures trade away exactness.
- Performance degrades in high dimensions because distances become less discriminative; feature selection or metric learning is often needed.
- Storing the entire training set as the model raises privacy concerns in sensitive domains.
- Predictions and their explanations are sensitive to the choice of k and the distance metric, both of which require tuning.
- Feature-level contributions and influence weights are design choices of specific variants rather than a single standard, so their fidelity to the prediction should be checked for each implementation.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Each prediction is linked to real training instances that a domain expert can inspect.
- The neighbor identities, labels and distances are the model's own computation, not an approximation of it, unlike post-hoc surrogate explanations.
- Feature-weighted distance makes the metric itself easier to audit, because the weights are visible.
- Counterfactual neighbors, meaning the nearest training instances whose label differs from the prediction, are drawn from the stored training set without fitting a separate explanation model, which can support case-level transparency.
- Mixed feature types can be handled when the distance metric is chosen to suit them.
Applications
- Medical diagnosis support where clinicians require nearest-case justifications for treatment recommendations.
- Credit and fraud risk scoring in regulated financial environments requiring auditability.
- Legal and judicial decision-support systems where reviewers need to examine the cases behind individual decisions.
- Educational assessment and student performance prediction with teacher-facing explanations.
- Anomaly detection with interpretable neighbor-based deviation scores.
How it works
How it works
For a query point, the distance to every training instance is computed with a chosen metric, such as Euclidean, Manhattan or Mahalanobis distance, or a learned metric. The Euclidean formula in the mechanics section is the default case. Because Euclidean distance is dominated by high-variance dimensions, continuous features should be standardised before it is applied, unless a feature-weighted variant is used. Feature-weighted variants multiply each dimension by an importance weight before the distance is computed, which makes the metric itself easier to inspect.
Formula
d(x, x_i) = \sqrt{\sum_{j=1}^{p}(x_j - x_{i,j})^2}The k training instances with the smallest distances form the neighborhood. The value of k sets the bias-variance trade-off: a small k follows local structure closely but varies more between similar queries, while a larger k smooths the decision. Explanation-oriented implementations report the exact distance to each retrieved neighbor and its rank.
KNN is a lazy learner: it has no training phase and keeps the training set itself, so all computation happens at query time. The formula in the mechanics section covers classification with an unweighted majority vote over the k neighbors' labels. If two or more labels receive the same vote count, the tie must be resolved by a fixed rule, such as preferring the label of the nearer neighbor, and that rule should be reported with the explanation. For regression, the mode is replaced by the mean of the neighbors' target values, a case the formula does not cover. Because the neighborhood is reported, the prediction can be traced to specific training cases.
Formula
\hat{y} = \text{mode}\{y_i : x_i \in N_k(x)\}The explanation reports the labels and distances of the k neighbors. Some variants also give a per-feature breakdown of how each dimension contributed to the distance, and some list the nearest training instances whose label differs from the prediction as counterfactual neighbors. Which of these outputs is available depends on the implementation. A recommended check, not an established standard, is to confirm three things for each reported explanation: that the listed neighbors are the k smallest distances under the stated metric, that the vote over their labels reproduces the prediction, and that each counterfactual neighbor carries a label different from the prediction.
Some variants assign each neighbor an influence weight that decreases with distance, for example inverse-distance weighting, and normalise these weights so they can be reported beside the prediction. Such weights can show which neighbors dominate a vote and can help reviewers inspect unusual training points. The weighting scheme is a design choice of the variant, not something fixed by the k-NN rule.
Common pitfalls
- Using Euclidean distance on mixed or unscaled features without standardization, producing distance values dominated by high-variance dimensions.
- Treating the nearest neighbor list as a full causal explanation rather than a similarity-based justification.
- Choosing k=1, which yields the most locally interpretable but most unstable predictions.
- Neglecting to validate that the retrieved neighbors are genuinely representative and not mislabeled outliers.
- Ignoring the privacy risk of exposing raw training records to end users in sensitive applications.
Frequently asked questions
Is KNN already explainable without any special extension?
Standard KNN is interpretable in the sense that each prediction rests on named training cases. XKNN variants add structured outputs, such as distances, influence weights, feature-level contributions and counterfactual neighbors, that make this case-based reasoning explicit and easier to present. The underlying prediction rule is the same.
How does XKNN differ from applying LIME or SHAP to a KNN model?
LIME and SHAP are model-agnostic post-hoc methods that approximate a model's behaviour, so their explanations can differ from what the model computes. Outputs read directly from the neighborhood, such as neighbor identity and distance, come from the model's own computation. Feature-level attributions in XKNN variants are a separate design choice and should be validated like any other explanation.
What is the best distance metric to use?
The choice depends on the features. Euclidean distance is usually applied to standardised continuous features. Manhattan distance is an alternative for continuous features, and Mahalanobis distance uses the feature covariance, so it accounts for correlations between features. For mixed feature types or high-dimensional data, a learned or specially designed metric may be needed. Compare candidate metrics by validation performance and by whether the neighbors look sensible to a domain expert.
How do I choose k for an explainable application?
Cross-validation is the usual way to select k for predictive accuracy. A smaller k gives a shorter neighbor list that is easier to inspect, but its predictions vary more and the explanation then describes fewer cases. Reporting the vote margin alongside the prediction helps show how much the neighborhood agrees.
Can XKNN help with GDPR transparency obligations?
Case-level neighbor explanations may help with transparency goals, but they do not by themselves guarantee compliance. The GDPR's provisions on automated decisions do not themselves require a case-level explanation, and whether a given explanation is sufficient depends on jurisdiction and decision context, so a legal expert should be consulted. Sharing raw training records may also introduce separate privacy risks, so privacy-preserving variants that anonymise or aggregate neighbor information may be preferable in sensitive deployments.
Related methods
Sources
Cover, T. & Hart, P. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21–27.
Open DOI referencePapernot, N. & McDaniel, P. (2018). Deep k-Nearest Neighbors: Towards Confident, Interpretable and Robust Deep Learning. arXiv preprint arXiv:1803.04765.
Open publication reference