Skip to main content

Logo


Python versions codecov PyPI version Docs

Conformal Anomaly Detection

Thresholds for anomaly detection are often arbitrary and lack theoretical guarantees. nonconform wraps anomaly detectors (from PyOD, scikit-learn, or custom implementations) and transforms their raw anomaly scores into conformal p-values. Under the assumptions of the selected method, these p-values support controlled false discovery rate (FDR) workflows with explicit, assumption-dependent guarantees.

Note: The methods in nonconform assume that training and test data are exchangeable. The package is therefore not suited for spatial or temporal autocorrelation unless such dependencies are explicitly handled in preprocessing or model design.

Guarantee scope: nonconform calibrates detector scores; it does not make an unsuitable detector or mismatched calibration set valid. Standard conformal claims require exchangeability. Weighted workflows require plausible covariate shift, support overlap, and reliable weights. FDR claims require valid p-values and the relevant multiple-testing assumptions.

Feature Overview

Need nonconform Functionality Start Here
Principled anomaly decisions ConformalDetector.select(...) combines conformal p-values with FDR-controlled selection FDR Control
Post-hoc threshold certificates conformal_fdp_upper_bound_from_result(...) attaches FDP and precision bounds to raw conformal p-value thresholds FDR Control
Flexible calibration strategies Split, CrossValidation, and JackknifeBootstrap for different data/compute tradeoffs Conformalization Strategies
Covariate-shift aware workflows Weighted conformal prediction with density-ratio estimators and weighted FDR control (requires sufficient calibration/test support overlap) Weighted Conformal
Rich p-value estimation Empirical, probabilistic KDE, and conditional calibration estimators Common Workflows
Sequential monitoring Randomized sequential ranks with exchangeability martingales (ExchangeabilityMonitor) Exchangeability Martingales
Custom detector integration Support for protocol-compliant detectors (with strict-inductive caveats for blocked PyOD models) Detector Compatibility

Citation

If you use nonconform in academic work, reports, or other published material, please cite the accompanying paper:

@misc{hennhoefer2026,
      title={Conformal Anomaly Detection in Python: Moving Beyond Heuristic Thresholds with 'nonconform'},
      author={Oliver Hennhöfer and Maximilian Kirsch and Christine Preisach},
      year={2026},
      eprint={2605.13642},
      archivePrefix={arXiv},
      primaryClass={stat.ML},
      url={https://arxiv.org/abs/2605.13642},
}

Getting Started

Installation via PyPI:

pip install nonconform

Note: The example below uses an external dataset API. Install with pip install oddball or pip install "nonconform[data]".

Classical Conformal Workflow

Example: Isolation Forest on the Shuttle benchmark. This trains a base detector, calibrates conformal scores, then applies FDR-controlled selection through select(...). Raw p-values remain available via detector.last_result.p_values.

from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Split
from nonconform.metrics import false_discovery_rate, statistical_power
from oddball import Dataset, load

x_train, x_test, y_test = load(Dataset.SHUTTLE, setup=True, seed=42)

detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    seed=42,
)
detector.fit(x_train)

decisions = detector.select(x_test, alpha=0.2)

print(f"Empirical FDR: {false_discovery_rate(y_test, decisions)}")
print(f"Statistical Power: {statistical_power(y_test, decisions)}")

Output:

Empirical FDR: 0.18
Statistical Power: 0.99

Advanced Methods

nonconform includes advanced workflows:

  • Weighted Conformal Prediction (weight_estimator=...): reweights calibration evidence for covariate shift settings where test and calibration distributions differ, assuming enough support overlap between calibration and test features.
  • Exchangeability Monitoring (nonconform.monitoring + nonconform.martingales): randomized sequential conformal ranks and anytime evidence monitoring over streams.

Weighted Conformal Setup:

from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Split, logistic_weight_estimator

detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    weight_estimator=logistic_weight_estimator(),
    seed=42,
)

Note: In weighted mode, ConformalDetector.select(...) dispatches weighted FDR control automatically.

Rigorous Sequential Monitoring from an Existing Split Detector:

import numpy as np
from pyod.models.iforest import IForest

from nonconform import ConformalDetector, Split
from nonconform.martingales import AlarmConfig, SimpleJumperMartingale
from nonconform.monitoring import ExchangeabilityMonitor

rng = np.random.default_rng(42)
x_train = rng.normal(size=(2_000, 5))
x_t = rng.normal(size=5)
x_stream_chunk = rng.normal(size=(10, 5))

alpha = 0.01
split_detector = ConformalDetector(
    detector=IForest(),
    strategy=Split(n_calib=1_000),
    seed=42,
).fit(x_train)
monitor = ExchangeabilityMonitor.from_split_detector(
    split_detector,
    martingale=SimpleJumperMartingale(
        alarm_config=AlarmConfig(restarted_ville_threshold=1 / alpha)
    ),
    seed=42,
)

state = monitor.update(x_t)
states = monitor.update_many(x_stream_chunk)

Note: from_split_detector(...) preserves the fitted split detector and primes sequential rank history from its calibration scores. Existing ConformalDetector.compute_p_value(...) behavior remains unchanged. Supplied conformalizers and martingales are copied so later caller mutations cannot alter monitor state. Use ville_threshold or restarted_ville_threshold when you need an anytime false-alarm bound for a monitored stream. CUSUM and Shiryaev-Roberts thresholds are change-evidence triggers for diagnosing possible stream changes; they need separate calibration and do not replace cross-hypothesis FDR control. See Exchangeability Martingales for threshold interpretation details.

Beyond Static Data

While primarily designed for static (single-batch) workflows, optional online-fdr integration supports streaming FDR procedures.

Custom Detectors

Any detector implementing the AnomalyDetector protocol can be integrated with nonconform:

from typing import Self

import numpy as np

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: ...

For custom detectors, either set score_polarity explicitly ("higher_is_anomalous" in most cases), or omit it to use the default score-polarity policy. Use score_polarity="auto" only when you want strict detector-family validation.

For strict inductive conformal/FDR pipelines, avoid batch-adaptive PyOD detectors with non-frozen score maps (for example ECOD and COPOD, which are blocked at runtime).

See Detector Compatibility for details and examples.

Optional Dependencies

For additional features, you might need optional dependencies:

  • pip install nonconform[pyod] - Includes PyOD anomaly detection library
  • pip install nonconform[data] - Includes oddball for loading benchmark datasets
  • pip install nonconform[fdr] - Includes advanced FDR control methods (online-fdr)
  • pip install nonconform[probabilistic] - Includes KDEpy and Optuna for probabilistic approximation
  • 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nonconform-1.1.1.tar.gz (67.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nonconform-1.1.1-py3-none-any.whl (74.3 kB view details)

Uploaded Python 3

File details

Details for the file nonconform-1.1.1.tar.gz.

File metadata

  • Download URL: nonconform-1.1.1.tar.gz
  • Upload date:
  • Size: 67.5 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

Hashes for nonconform-1.1.1.tar.gz
Algorithm Hash digest
SHA256 1c4369d74690bb78708713338bf22df21967cca5192442693ffdc0cb451a3be2
MD5 63b1af469a410f5391c6ab6df8cae317
BLAKE2b-256 6543916d16f2cd3cefca25a1fc2b194a14318b9d2fc3804d79fdbbb7cd4e22a6

See more details on using hashes here.

File details

Details for the file nonconform-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: nonconform-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 74.3 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

Hashes for nonconform-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a7c514a1d1f7c97bd7fe7171f827a3d27a36ac6120bffa2c4ee23a09af954609
MD5 c5500816c038e1a0e66ae4c6fe319ae0
BLAKE2b-256 cc929b42eeab22c3cfaff31cdfc858a9f897fab3d6645e20ab3a210e849cd022

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page