Skip to main content

knnn

K-Nearest Neighbors of Neighbors - for Anomaly Detection

pip install knnn
k-NN

k-NN

k-NNN

k-NNN

Description

This package provides a simple implementation of the K-Nearest Neighbors of Neighbors algorithm. The algorithm is a simple extension of the K-Nearest Neighbors algorithm, which is used for anomaly detection. The algorithm is based on the idea that the neighbors of the neighbors of a point gives more information than its neighbors. The algorithm can be used to improve the accuracy of the KNN algorithm.

Usage

from knnn import KNNN
import numpy as np

# Random data
x_normal = np.random.rand(100, 5)
x_test = np.random.rand(20, 5) + 1

# Create a KNNN object
knnn = KNNN(number_of_neighbors=3, number_of_neighbors_of_neighbors=25)
# Fit the model
knnn.fit(x_normal)
# Calculate anomaly scores (larger means more anomalous)
y_pred = knnn.predict(x_test)

Installation

The simplest way to install the package is to run:

pip install knnn

If you want to install the latest version from the main branch:

(-e option will allow you to change the code without reinstalling the package)

git clone https://github.com/Onr/knnn.git
cd knnn
python3 -m pip install -e ".[dev]"

If you want to build the package from source, run:

python3 -m build

and to install the built package, run:

python3 -m pip install --force-reinstall dist/knnn-0.1.0-py3-none-any.whl

To run the tests, run:

python3 -m pytest -m "not benchmark and not external"

Scoring and compatibility

Version 0.1.0 keeps L2 Mahalanobis scoring as the default (p=2), expressed as RMS standardized eigenvector projections within each block. Numerically singular local covariances use Euclidean distances, following the original estimator's identity-matrix fallback. Select p=1 for the paper's absolute projections divided by the square root of each local covariance eigenvalue. Both modes weight block scores by their feature counts and average over neighbors. Existing thresholds should be recalibrated because grouping, partial blocks and score normalization have changed.

L1 scoring is an explicit option: the audit's double-root bug is absent from v0.0.9, and strict inverse-variance weighting of singular sparse neighborhoods reduced accuracy in the Digits comparison. Exact scoring is not a guarantee of higher accuracy on every dataset.

Features are greedily grouped by absolute correlation into blocks of at most set_size dimensions. All features are retained, including a smaller final block. Use set_size=-1 for a single block. Constant features are supported; a query that changes a feature that was constant during training receives the largest finite float score, as in the previous release.

batch_size=256 bounds temporary covariance and projection arrays during fit and inference. Stored eigenvectors still require O(N × D × set_size) memory. Neighbor counts are capped to the available training samples without changing constructor parameters. At least two samples are needed per fitted model.

KNNN.predict(X) and KNNN(X) continue to return continuous anomaly scores. KNNN.score_samples(X) returns their negatives, so higher means more normal. KNNN supports sklearn cloning, pipelines and parameter searches; pass an explicit scoring function to GridSearchCV. It does not implement sklearn's thresholded OutlierMixin contract.

For classification, use the sklearn-compatible estimator:

from knnn import KNNNClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

classifier = make_pipeline(
    StandardScaler(), KNNNClassifier(distance_function="euclidean")
)
classifier.fit(X_train, y_train)
labels = classifier.predict(X_test)

Class columns follow sorted classes_. predict_proba returns votes for the minimum-score classes, splitting ties equally; these are not calibrated probabilities. The original KNNN_class(number_of_classes=...) callable and its tuple results are retained.

The estimator now uses scikit-learn for nearest neighbors. Runtime dependencies are NumPy and scikit-learn (plus their transitive dependencies). The legacy get_features_knn_faiss helper requires pip install "knnn[faiss]". Diagnostic knn_distance values retain cosine distances or squared Euclidean distances; the legacy dictionary key knn_indeises is retained.

Development and release

python3 -m pip install -e ".[dev]"
python3 -m pytest -m "not benchmark and not external"
python3 -m build
python3 -m twine check dist/knnn-0.1.0*

The comparative benchmarks assert that k-NNN outperforms k-NN on particular samples; they are marked benchmark. Run them with python3 -m pytest -m "benchmark and not external". These comparisons can fail when k-NNN ties or underperforms k-NN; they are not correctness guarantees. Tests marked external require Hugging Face downloads or local ADB datasets. Set KNNN_ADB_DATASET_PATH to the directory containing the ADB dataset folders; missing local datasets are reported as skipped.

Release files are dist/knnn-0.1.0-py3-none-any.whl and dist/knnn-0.1.0.tar.gz. Install the wheel directly with:

python3 -m pip install dist/knnn-0.1.0-py3-none-any.whl

Cite

@inproceedings{nizan2024k,
  title={k-NNN: Nearest Neighbors of Neighbors for Anomaly Detection},
  author={Nizan, Ori and Tal, Ayellet},
  booktitle={Proceedings of the IEEE/CVF Winter Conference on Applications of Computer Vision (WACV) Workshops},
  pages={1005--1014},
  year={2024}
}

Metadata

Release files for knnn 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for knnn 0.1.0
File Size Uploaded Provenance Actions
knnn-0.1.0.tar.gz 31.6 kB Without provenance Details for knnn-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for knnn 0.1.0
File Interpreter ABI Platform Actions
knnn-0.1.0-py3-none-any.whl Python 3 none any Details for knnn-0.1.0-py3-none-any.whl

Total release size: 45.3 kB

Release files / knnn-0.1.0.tar.gz

Download URL knnn-0.1.0.tar.gz
Size 31.6 kB
Tags Source
SHA-256 checksum
How to use checksums
f81d33fc8d2c0fdea218f1d1761b084bda5a1ed64218f49db6633ece55ece896
BLAKE2b-256 checksum
How to use checksums
a07aa00041ee0c4f9ebb7cc7106fe72305aad5a6670d5b9b5df099ba570f2f5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.4

Release files / knnn-0.1.0-py3-none-any.whl

Download URL knnn-0.1.0-py3-none-any.whl
Size 13.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4589fcf927feed42bca22292da7181d06aa5ff1c13ac5286fd4507168c4700c7
BLAKE2b-256 checksum
How to use checksums
51d607ee7d21456ab7c2548432b3a31965856548af4037af5d70ec3a5b286798
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.4

Security for knnn 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page