Clustering, density estimation, and anomaly detection · Anomaly detection · UCL061 · Algorithm
K-nearest-neighbor distance detector
Rank cases by distance to nearby reference observations. It is a transparent baseline when normal data occupy well-supported regions under a meaningful metric.
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Image inspection anomalies (PaDiM, kNN) Experimental
- Nearest-neighbor outlier scores Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- Verified in Python and R through discover.knn_outlier. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Rank cases by distance to nearby reference observations. It is a transparent baseline when normal data occupy well-supported regions under a meaningful metric.
Question / hypotheses
Which observations deviate from the chosen reference notion of normality, and at what operational alert rate? This entry defines an estimation or optimization objective, not an intrinsic null/alternative hypothesis test.
Architecture / computational structure
A reference set, distance search, and a selected neighbor-distance statistic.
Assumptions
For training-point scores, remove the point's own zero-distance match. In high dimensions, irrelevant features and distance concentration can degrade ranking. A rare coherent group may be normal but distant from the main population.
Formula / computational definition
A common definition is , where is the th nearest reference point. Other versions average or maximize neighbor distances; they must be named when comparing results. This score is related to local sparsity but is not automatically a normalized density or probability.
Parameters and notation
Learned or fitted quantities: Retained reference observations and a calibrated threshold. User-set hyperparameters/design choices: Choose , metric, feature scaling, reference sample, and approximate-search accuracy. Tune these against the stated objective and stability/validation criteria; do not select settings on the final evaluation set.
Fitting, fine-tuning, and adaptation
Neural fine-tuning is not applicable to this classical detector. Refit the reference model when its population changes, then recalibrate an alert threshold on a separate normal holdout. Tune sensitivity without using final-test anomaly labels repeatedly.
How to use and calibrate
Use normal-only holdout calibration, ranking metrics on a separate labeled test set, and sensitivity to . Examine nearest neighbors to explain each alert. Search approximation should be evaluated for score stability, not just speed.
Example application
Flag observations far from a normal reference collection. Define the reference population, measurement units, and success criterion before fitting; investigate whether discovered groups or alerts reflect the intended phenomenon.
Interpretation / pitfalls
Watch out
The reported result is conditional on the representation and objective. An alert is a screening result, not a diagnosis or a calibrated posterior probability. Evaluate both ranking and the decision threshold.
Python and R code examples
Implement distances with SciPy or NumPy and partial sorting; R can use base matrix operations for small examples. Lab 2 supplies complete paired implementations and finite-sample normal-reference calibration.
Component: KNN distance scoring against a separate training reference. Python: executed successfully; R: not executed (Rscript unavailable). These small fixtures establish the arithmetic operation, not full-method accuracy or reproduction of paper results.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — KNN distance scoring against a separate training reference. · needs numpy
import numpy as np
reference=np.array([0.,.2,.4,1.]); query=np.array([.1,3.]); k=2
D=np.abs(query[:,None]-reference); result=np.partition(D,k-1,axis=1)[:,k-1]
print(result)
Component demo, not a trained model — KNN distance scoring against a separate training reference.
reference=c(0,.2,.4,1); query=c(.1,3); k=2
D=abs(outer(query,reference,'-')); result=apply(D,1,function(d) sort(d)[k])
print(result)
Sources
- Source 1pyod.readthedocs.io
From the CodeSplash reference, entry UCL061.