Conformal Anomaly Detection
Project description
Conformal Anomaly Detection
Thresholds for anomaly detection are often arbitrary and lack theoretical guarantees about the anomalies they identify. nonconform wraps anomaly detectors—from PyOD, scikit-learn, or custom implementations—and transforms their raw anomaly scores into statistically valid $p$-values. It applies principles from conformal prediction [Vovk et al., 2005] to the setting of one-class classification, enabling anomaly detection with provable statistical guarantees [Bates et al., 2023] and a controlled false discovery rate [Benjamini & Hochberg, 1995].
Note: The methods in nonconform assume that training and test data are exchangeable [Vovk et al., 2005]. Therefore, the package is not suited for data with spatial or temporal autocorrelation unless such dependencies are explicitly handled in preprocessing or model design.
:hatching_chick: Getting Started
Installation via PyPI:
pip install nonconform
Note: The following examples use an external dataset API. Install with
pip install oddballorpip install "nonconform[data]"to include it. (see Optional Dependencies)
Classical (Conformal) Approach
Example: Detecting anomalies with Isolation Forest on the Shuttle dataset. The approach splits data for calibration, trains the model, then converts anomaly scores to p-values by comparing test scores against the calibration distribution.
from pyod.models.iforest import IForest
from scipy.stats import false_discovery_control
from nonconform.strategy import Split
from nonconform.detection import ConformalDetector
from oddball import Dataset, load
from nonconform.utils.stat import false_discovery_rate, statistical_power
x_train, x_test, y_test = load(Dataset.SHUTTLE, setup=True, seed=42)
estimator = ConformalDetector(
detector=IForest(behaviour="new"), strategy=Split(n_calib=1_000), seed=42)
estimator.fit(x_train)
estimates = estimator.predict(x_test)
decisions = false_discovery_control(estimates, method='bh') <= 0.2
print(f"Empirical False Discovery Rate: {false_discovery_rate(y=y_test, y_hat=decisions)}")
print(f"Empirical Statistical Power (Recall): {statistical_power(y=y_test, y_hat=decisions)}")
Output:
Empirical False Discovery Rate: 0.18
Empirical Statistical Power (Recall): 0.99
:hatched_chick: Advanced Methods
Two advanced approaches are implemented that may increase the power of a conformal anomaly detector:
- A KDE-based (probabilistic) approach that models the calibration scores to achieve continuous $p$-values in contrast to the standard empirical distribution function.
- A weighted approach that prioritizes calibration scores by their similarity to the test batch at hand and is more robust to covariate shift between test and calibration data. Maybe combine with the probabilistic approach.
Probabilistic Conformal Approach:
estimator = ConformalDetector(
detector=HBOS(),
strategy=Split(n_calib=1_000),
estimation=Probabilistic(n_trials=10), # KDE Tuning Trials
seed=1,
)
Weighed Conformal Anomaly Detection:
# Weighted conformal (with covariate shift handling):
from nonconform.detection.weight import LogisticWeightEstimator
estimator = ConformalDetector(
detector=IForest(behaviour="new"), strategy=Split(n_calib=1_000), weight_estimator=LogisticWeightEstimator(seed=42), seed=42)
Note: Weighted procedures require weighted FDR control for statistical validity (see
weighted_bh()orweighted_false_discovery_control()).
Beyond Static Data
While primarily designed for static (single-batch) applications, the library supports streaming scenarios through BatchGenerator() and OnlineGenerator(). For statistically valid FDR control in streaming data, use the optional onlineFDR dependency, which implements appropriate statistical methods.
Custom Detectors
Any detector implementing the AnomalyDetector protocol works with nonconform:
class MyDetector:
def fit(self, X, y=None) -> Self: ...
def decision_function(self, X) -> np.ndarray: ... # higher = more anomalous
def get_params(self, deep=True) -> dict: ...
def set_params(self, **params) -> Self: ...
See Detector Compatibility for details and examples.
Citation
If you find this repository useful for your research, please cite the following papers:
Leave-One-Out-, Bootstrap- and Cross-Conformal Anomaly Detectors
@inproceedings{Hennhofer2024,
title = {{ Leave-One-Out-, Bootstrap- and Cross-Conformal Anomaly Detectors }}, author = {Hennhofer, Oliver and Preisach, Christine}, year = 2024, month = {Dec}, booktitle = {2024 IEEE International Conference on Knowledge Graph (ICKG)}, publisher = {IEEE Computer Society}, address = {Los Alamitos, CA, USA}, pages = {110--119}, doi = {10.1109/ICKG63256.2024.00022}, url = {https://doi.ieeecomputersociety.org/10.1109/ICKG63256.2024.00022}}
Testing for Outliers with Conformal p-Values
@article{Bates2023,
title = {Testing for outliers with conformal p-values}, author = {Bates, Stephen and Candès, Emmanuel and Lei, Lihua and Romano, Yaniv and Sesia, Matteo}, year = 2023, month = feb, journal = {The Annals of Statistics}, publisher = {Institute of Mathematical Statistics}, volume = 51, number = 1, doi = {10.1214/22-aos2244}, issn = {0090-5364}, url = {http://dx.doi.org/10.1214/22-AOS2244}}
Optional Dependencies
For additional features, you might need optional dependencies:
pip install nonconform[pyod]- Includes PyOD anomaly detection librarypip install nonconform[data]- Includes oddball for loading benchmark datasetspip install nonconform[fdr]- Includes advanced FDR control methods (online-fdr)pip install nonconform[all]- Includes all optional dependencies
Please refer to the pyproject.toml for details.
Contact
Bug reporting: https://github.com/OliverHennhoefer/nonconform/issues
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file nonconform-0.96.0.tar.gz.
File metadata
- Download URL: nonconform-0.96.0.tar.gz
- Upload date:
- Size: 417.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
42e78aff8ea01900efcf3a6d80a869fd315c3b9460e7906be99e05739c3cc98a
|
|
| MD5 |
20c8662dab934906f8c175b07eb97a26
|
|
| BLAKE2b-256 |
fd27c32498b2b9810dd953dd1c8c454787e549c9b48276e0e35c7b38fd579ccb
|
File details
Details for the file nonconform-0.96.0-py3-none-any.whl.
File metadata
- Download URL: nonconform-0.96.0-py3-none-any.whl
- Upload date:
- Size: 60.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.9 {"installer":{"name":"uv","version":"0.9.9"},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0dee5fa89df5bbef742e4d98cfc33542912f8a69199c516788dc4f7b209f51a3
|
|
| MD5 |
ab07065a407922867654237044432327
|
|
| BLAKE2b-256 |
86463e69c4d4ae57236778ef55d27c42ecc93b2daf13fe0b3835376c6cb545a9
|