Skip to content

Detectors API

Base classes

anomalybench.analytics.base

BaseDetector

Bases: ABC

Common interface for all anomaly detectors.

Detector implementations expose a three-step lifecycle:

  • fit(data, **params) trains the detector and marks it as fitted.
  • score(data) returns detector-specific anomaly scores and requires a successful prior fit.
  • detect_anomalies(data, **params) is the fit-and-score convenience path used by the benchmark CLI.

is_fitted property

is_fitted: bool

Return whether the detector has completed a successful fit.

preprocessing_pipeline property

preprocessing_pipeline: PreprocessingPipeline | None

Return the currently configured preprocessing pipeline.

set_preprocessing_pipeline

set_preprocessing_pipeline(pipeline: PreprocessingPipeline | None) -> None

Attach a preprocessing pipeline used prior to model training.

fit_preprocessed

fit_preprocessed(data: Any, **params: Any)

Fit the detector after applying the preprocessing pipeline.

score_preprocessed

score_preprocessed(data: Any)

Score data after applying the preprocessing pipeline.

get_name abstractmethod

get_name() -> str

Return human readable detector name.

fit abstractmethod

fit(data, **params)

Fit the detector to the provided data.

score abstractmethod

score(data)

Return anomaly scores for the provided data.

detect_anomalies

detect_anomalies(data, **params)

Fit and return raw scores carrying their orientation metadata.

OrientedScores

Bases: ndarray

NumPy score array carrying detector score and alignment metadata.

coerce_tabular_2d

coerce_tabular_2d(data: DataFrame | Any, *, detector_name: str = 'Detector', allow_empty: bool = False) -> TabularArray

Return a dense 2-D floating-point array for tabular detectors.

Registry

anomalybench.analytics.detectors.registry

register_detector

register_detector(name: str, path: str, *, allow_override: bool = False) -> None

Register a detector class by dotted module path.

get_detector_class

get_detector_class(name: str) -> type[BaseDetector]

Return the detector class associated with name.

Detector implementations

Classical

anomalybench.analytics.detectors.classical

Classical anomaly detectors built on scikit-learn and PyOD.

Each detector exposes a ~anomalybench.analytics.base.BaseDetector interface with fit and score methods. The implementations avoid importing optional dependencies until required to keep the package lightweight.

IsolationForestDetector

Bases: BaseDetector

Wrapper around scikit-learn's IsolationForest.

Instances are created without constructor parameters. Provide estimator options when calling fit.

fit returns the fitted detector; score returns decision function values as numpy.ndarray.

Attributes:

Name Type Description
model

The fitted IsolationForest estimator once fit is called.

Examples:

>>> detector = IsolationForestDetector()
>>> _ = detector.fit(X_train)
>>> scores = detector.score(X_test)
>>> scores.shape
(len(X_test),)

fit

fit(data: FrameOrArray, **params: Any) -> IsolationForestDetector

Fit the isolation forest model to the provided data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

A 2D array-like object containing the training observations, shaped (n_samples, n_features).

required
**params Any

Additional keyword arguments forwarded to sklearn.ensemble.IsolationForest.

{}

Returns:

Name Type Description
IsolationForestDetector IsolationForestDetector

The fitted detector instance.

Examples:

>>> detector = IsolationForestDetector()
>>> detector.fit(X_train, n_estimators=200)
IsolationForestDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Compute anomaly scores for new observations.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples shaped (n_samples, n_features) to evaluate with the fitted estimator.

required

Returns:

Type Description
ScoreArray

numpy.ndarray: The isolation forest decision function values where

ScoreArray

higher scores indicate more normal observations.

Examples:

>>> detector = IsolationForestDetector().fit(X_train)
>>> detector.score(X_test)
array([...])

LOFDetector

Bases: BaseDetector

Local Outlier Factor implementation allowing new data scoring.

Instances require no constructor parameters; pass LOF settings to fit.

fit returns the fitted detector; score returns local outlier factor scores as list[float].

Attributes:

Name Type Description
lof

The anomalybench.analytics.lof.LOF instance trained during fit.

min_pts

Minimum number of neighbors used when computing the local outlier factor.

Examples:

>>> detector = LOFDetector()
>>> _ = detector.fit(X_train_df, min_pts=5)
>>> detector.score(X_test_df)[0]
-0.23

fit

fit(data: DataFrame, normalize: bool = False, **params: Any) -> LOFDetector

Compute the LOF model for the given tabular data.

Parameters:

Name Type Description Default
data DataFrame

A DataFrame containing the observations used for training. Column order is preserved in the internal representation.

required
normalize bool

Whether to apply LOF's internal normalization routine. Defaults to False.

False
**params Any

Additional parameters such as min_pts forwarded to anomalybench.analytics.lof.LOF.

{}

Returns:

Name Type Description
LOFDetector LOFDetector

The fitted detector instance.

Examples:

>>> detector = LOFDetector()
>>> detector.fit(X_train_df, normalize=True, min_pts=10)
LOFDetector(...)

score

score(data: DataFrame) -> list[float]

Evaluate new observations using the trained LOF model.

Parameters:

Name Type Description Default
data DataFrame

A DataFrame shaped (n_samples, n_features) with the same schema as the training data.

required

Returns:

Type Description
list[float]

list[float]: Negative local outlier factor values where larger values correspond to less anomalous points.

Examples:

>>> detector = LOFDetector().fit(X_train_df, min_pts=5)
>>> detector.score(X_test_df)[:3]
[-0.2, -0.5, -0.1]

SOSDetector

Bases: BaseDetector

Stochastic Outlier Selection using the sksos package.

Constructed without arguments; configure hyper-parameters via fit.

fit returns the fitted detector; score returns SOS anomaly probabilities as numpy.ndarray.

Attributes:

Name Type Description
model

The wrapped sksos.SOS estimator.

X

Cached training data used when scoring without new data.

Examples:

>>> detector = SOSDetector()
>>> _ = detector.fit(X_train_df, perplexity=15)
>>> detector.score()[:3]
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> SOSDetector

Fit the SOS model on dense feature data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples of shape (n_samples, n_features).

required
**params Any

Optional SOS hyper-parameters such as perplexity or metric.

{}

Returns:

Name Type Description
SOSDetector SOSDetector

The fitted detector instance.

Examples:

>>> detector = SOSDetector()
>>> detector.fit(X_train_df, perplexity=50, metric="cosine")
SOSDetector(...)

score

score(data: FrameOrArray | None = None) -> ScoreArray

Score data using the fitted SOS model.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to score. If None, the training data provided to fit is used.

None

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative SOS probabilities where larger values indicate more anomalous observations.

Examples:

>>> detector = SOSDetector().fit(X_train_df)
>>> detector.score(X_test_df)
array([...])

EnsembleDetector

Bases: BaseDetector

Simple ensemble averaging KNN, SOS and HBOS scores.

Instances are parameter-free; supply detector configurations when calling fit.

fit returns the fitted detector; score returns aggregated anomaly scores as numpy.ndarray.

Attributes:

Name Type Description
knn

Fitted KNNDetector component.

sos

Fitted SOSDetector component.

hbos

Fitted HBOSDetector component.

Examples:

>>> detector = EnsembleDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> EnsembleDetector

Train the constituent detectors and cache them for scoring.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training data matrix of shape (n_samples, n_features).

required
**params Any

Keyword arguments forwarded to each base detector.

{}

Returns:

Name Type Description
EnsembleDetector EnsembleDetector

The fitted ensemble instance.

Examples:

>>> detector = EnsembleDetector()
>>> detector.fit(X_train, k=10)
EnsembleDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Combine component detector scores by normalized averaging.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to be scored, shaped (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Aggregated anomaly scores where lower values imply more anomalous points.

Examples:

>>> detector = EnsembleDetector().fit(X_train)
>>> detector.score(X_test)[:5]
array([...])

HBOSDetector

Bases: BaseDetector

Histogram-Based Outlier Score with vectorized scoring.

Instantiate without arguments and configure via fit.

fit returns the fitted detector; score returns log-density scores as numpy.ndarray.

Attributes:

Name Type Description
edges_left

Left bin edges for each feature.

edges_right

Right bin edges for each feature.

hist

Density estimates for each histogram bin.

log_hist

Log-density used for additive scoring.

Examples:

>>> detector = HBOSDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> HBOSDetector

Estimate per-feature histograms with adaptive binning.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples in a 2D structure of shape (n_samples, n_features).

required
**params Any

Additional configuration such as k for the number of bins.

{}

Returns:

Name Type Description
HBOSDetector HBOSDetector

The fitted detector instance.

Examples:

>>> detector = HBOSDetector()
>>> detector.fit(X_train, k=5)
HBOSDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Evaluate the log-density based HBOS score for each sample.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples compatible with the histogram features used during fitting.

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Log-probabilities where lower values indicate anomalies.

Examples:

>>> detector = HBOSDetector().fit(X_train)
>>> detector.score(X_test)[:2]
array([-12.5, -10.7])

KNNDetector

Bases: BaseDetector

K-Nearest Neighbors distance-based detector.

The detector is created without constructor parameters; set k and other options via fit.

fit returns the fitted detector; score returns summed distance scores as numpy.ndarray.

Attributes:

Name Type Description
k

Number of neighbors considered for scoring.

neigh

Fitted sklearn.neighbors.NearestNeighbors estimator.

Examples:

>>> detector = KNNDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> KNNDetector

Fit the nearest neighbor index on the training data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training matrix with shape (n_samples, n_features).

required
**params Any

Optional parameters, including k for the number of neighbors.

{}

Returns:

Name Type Description
KNNDetector KNNDetector

The fitted detector instance.

Examples:

>>> detector = KNNDetector()
>>> detector.fit(X_train, k=10)
KNNDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Score samples based on summed neighbor distances.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to evaluate with shape (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative summed distances, where smaller values indicate potential anomalies.

Examples:

>>> detector = KNNDetector().fit(X_train, k=5)
>>> detector.score(X_test)[:3]
array([-4.2, -3.1, -5.0])

OneClassSVMDetector

Bases: BaseDetector

Wrapper around sklearn.svm.OneClassSVM.

Instances require no constructor parameters; configure the SVM via fit.

fit returns the fitted detector; score returns decision function scores as numpy.ndarray.

Attributes:

Name Type Description
model

The fitted one-class SVM estimator.

Examples:

>>> detector = OneClassSVMDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> OneClassSVMDetector

Train a one-class SVM on the input data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples with shape (n_samples, n_features).

required
**params Any

Keyword arguments for sklearn.svm.OneClassSVM.

{}

Returns:

Name Type Description
OneClassSVMDetector OneClassSVMDetector

The fitted detector instance.

Examples:

>>> detector = OneClassSVMDetector()
>>> detector.fit(X_train, kernel="rbf", gamma=0.1)
OneClassSVMDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Compute signed distance to the SVM decision boundary.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to score with shape (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Decision function scores where larger values denote inliers.

Examples:

>>> detector = OneClassSVMDetector().fit(X_train)
>>> detector.score(X_test)
array([...])

DBSCANDetector

Bases: BaseDetector

Density-based spatial clustering anomaly detector.

Instantiate without arguments; configure clustering options in fit.

fit returns the fitted detector; score returns binary anomaly indicators as numpy.ndarray.

Attributes:

Name Type Description
model

The sklearn.cluster.DBSCAN estimator fitted to the training data.

Examples:

>>> detector = DBSCANDetector()
>>> _ = detector.fit(X_train, eps=0.5)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> DBSCANDetector

Cluster the training data using DBSCAN.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Observations of shape (n_samples, n_features).

required
**params Any

Keyword arguments forwarded to sklearn.cluster.DBSCAN.

{}

Returns:

Name Type Description
DBSCANDetector DBSCANDetector

The fitted detector instance.

Examples:

>>> detector = DBSCANDetector()
>>> detector.fit(X_train, eps=0.8, min_samples=5)
DBSCANDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Assign anomaly labels based on DBSCAN clustering.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to cluster, shaped (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Binary scores where 1.0 represents an outlier and 0.0 an inlier.

Examples:

>>> detector = DBSCANDetector().fit(X_train, eps=0.6)
>>> detector.score(X_test)[:4]
array([0., 1., 0., 0.])

EllipticEnvelopeDetector

Bases: BaseDetector

Robust covariance estimate assuming Gaussian distributed data.

Instances are created without arguments; pass covariance options via fit.

fit returns the fitted detector; score returns decision scores as numpy.ndarray.

Attributes:

Name Type Description
model

The fitted sklearn.covariance.EllipticEnvelope estimator.

Examples:

>>> detector = EllipticEnvelopeDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> EllipticEnvelopeDetector

Estimate a robust covariance model for Gaussian-like data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training matrix of shape (n_samples, n_features).

required
**params Any

Parameters to initialize sklearn.covariance.EllipticEnvelope.

{}

Returns:

Name Type Description
EllipticEnvelopeDetector EllipticEnvelopeDetector

The fitted detector instance.

Examples:

>>> detector = EllipticEnvelopeDetector()
>>> detector.fit(X_train, contamination=0.1)
EllipticEnvelopeDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Compute distances to the robust covariance contour.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to score shaped (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Decision function values where larger scores signify more typical observations.

Examples:

>>> detector = EllipticEnvelopeDetector().fit(X_train)
>>> detector.score(X_test)
array([...])

GaussianMixtureDetector

Bases: BaseDetector

Gaussian Mixture negative log-likelihood as anomaly score.

Instantiate without parameters; provide mixture settings via fit.

fit returns the fitted detector; score returns negative log-likelihood scores as numpy.ndarray.

Attributes:

Name Type Description
model

The fitted sklearn.mixture.GaussianMixture estimator.

Examples:

>>> detector = GaussianMixtureDetector()
>>> _ = detector.fit(X_train, n_components=3)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> GaussianMixtureDetector

Fit a Gaussian mixture model to the training samples.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training data shaped (n_samples, n_features).

required
**params Any

Parameters passed to sklearn.mixture.GaussianMixture.

{}

Returns:

Name Type Description
GaussianMixtureDetector GaussianMixtureDetector

The fitted detector instance.

Examples:

>>> detector = GaussianMixtureDetector()
>>> detector.fit(X_train, n_components=2, covariance_type="diag")
GaussianMixtureDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Return negative log-likelihood scores for the provided data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples shaped (n_samples, n_features) to evaluate with the fitted model.

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative log probabilities where larger values imply more anomalous points.

Examples:

>>> detector = GaussianMixtureDetector().fit(X_train)
>>> detector.score(X_test)[:4]
array([...])

SklearnLOFDetector

Bases: BaseDetector

Scikit-learn's LOF with novelty mode for scoring new data.

Instances do not require constructor parameters; pass LOF options to fit.

fit returns the fitted detector; score returns novelty detection scores as numpy.ndarray.

Attributes:

Name Type Description
model

The sklearn.neighbors.LocalOutlierFactor estimator configured with novelty=True.

Examples:

>>> detector = SklearnLOFDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> SklearnLOFDetector

Train scikit-learn's LOF implementation in novelty mode.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples shaped (n_samples, n_features).

required
**params Any

Additional parameters for sklearn.neighbors.LocalOutlierFactor.

{}

Returns:

Name Type Description
SklearnLOFDetector SklearnLOFDetector

The fitted detector instance.

Examples:

>>> detector = SklearnLOFDetector()
>>> detector.fit(X_train, n_neighbors=40)
SklearnLOFDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Score samples using the LOF decision function.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples for evaluation of shape (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Signed LOF scores where higher values indicate less anomalous observations.

Examples:

>>> detector = SklearnLOFDetector().fit(X_train)
>>> detector.score(X_test)
array([...])

KMeansDetector

Bases: BaseDetector

Distance to nearest KMeans centroid as anomaly score.

Construct instances without parameters; choose n_clusters via fit.

fit returns the fitted detector; score returns negative centroid distances as numpy.ndarray.

Attributes:

Name Type Description
n_clusters

Number of centroids used during fitting.

kmeans

The fitted sklearn.cluster.KMeans estimator.

Examples:

>>> detector = KMeansDetector()
>>> _ = detector.fit(X_train, n_clusters=5)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> KMeansDetector

Train KMeans on the provided data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Observations shaped (n_samples, n_features).

required
**params Any

Optional KMeans parameters, such as n_clusters.

{}

Returns:

Name Type Description
KMeansDetector KMeansDetector

The fitted detector instance.

Examples:

>>> detector = KMeansDetector()
>>> detector.fit(X_train, n_clusters=3)
KMeansDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Score samples by their distance to the closest centroid.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples shaped (n_samples, n_features) consistent with the training data.

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative minimum distances where lower values denote more anomalous points.

Examples:

>>> detector = KMeansDetector().fit(X_train, n_clusters=4)
>>> detector.score(X_test)[:3]
array([-0.4, -0.7, -1.2])

PCAReconstructionDetector

Bases: BaseDetector

Use PCA reconstruction error as anomaly score.

Instantiate without arguments; configure PCA via fit.

fit returns the fitted detector; score returns negative reconstruction errors as numpy.ndarray.

Attributes:

Name Type Description
n_components

Number (or fraction) of principal components retained.

pca

The fitted sklearn.decomposition.PCA transformer.

Examples:

>>> detector = PCAReconstructionDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> PCAReconstructionDetector

Fit PCA to approximate the training data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples with shape (n_samples, n_features).

required
**params Any

Optional PCA parameters including n_components.

{}

Returns:

Name Type Description
PCAReconstructionDetector PCAReconstructionDetector

The fitted detector instance.

Examples:

>>> detector = PCAReconstructionDetector()
>>> detector.fit(X_train, n_components=0.9)
PCAReconstructionDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Compute negative reconstruction error for each sample.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples shaped (n_samples, n_features) to evaluate.

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative L2 reconstruction errors where smaller values indicate more anomalous observations.

Examples:

>>> detector = PCAReconstructionDetector().fit(X_train)
>>> detector.score(X_test)[:5]
array([-0.2, -1.4, ...])

MahalanobisDetector

Bases: BaseDetector

Mahalanobis distance using empirical covariance.

Create detector without parameters; configure covariance options via fit.

fit returns the fitted detector; score returns negative distance scores as numpy.ndarray.

Attributes:

Name Type Description
cov

The fitted sklearn.covariance.EmpiricalCovariance estimator.

Examples:

>>> detector = MahalanobisDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> MahalanobisDetector

Estimate the covariance matrix for Mahalanobis scoring.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training samples shaped (n_samples, n_features).

required
**params Any

Optional arguments passed to sklearn.covariance.EmpiricalCovariance.

{}

Returns:

Name Type Description
MahalanobisDetector MahalanobisDetector

The fitted detector instance.

Examples:

>>> detector = MahalanobisDetector()
>>> detector.fit(X_train)
MahalanobisDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Compute negative Mahalanobis distance for each sample.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to evaluate with shape (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Negative distances where smaller (more negative) values indicate greater anomaly likelihood.

Examples:

>>> detector = MahalanobisDetector().fit(X_train)
>>> detector.score(X_test)[:3]
array([-5.3, -4.1, -3.0])

KDEDetector

Bases: BaseDetector

Kernel Density Estimator returning log-density scores.

Instantiate without parameters; set KDE options via fit.

fit returns the fitted detector; score returns log-density scores as numpy.ndarray.

Attributes:

Name Type Description
kde

The fitted sklearn.neighbors.KernelDensity estimator.

Examples:

>>> detector = KDEDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])

fit

fit(data: FrameOrArray, **params: Any) -> KDEDetector

Fit a kernel density estimator to the training data.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Training observations with shape (n_samples, n_features).

required
**params Any

Keyword arguments for sklearn.neighbors.KernelDensity.

{}

Returns:

Name Type Description
KDEDetector KDEDetector

The fitted detector instance.

Examples:

>>> detector = KDEDetector()
>>> detector.fit(X_train, bandwidth=0.5)
KDEDetector(...)

score

score(data: FrameOrArray) -> ScoreArray

Evaluate log-density scores for the provided samples.

Parameters:

Name Type Description Default
data DataFrame or ndarray

Samples to score shaped (n_samples, n_features).

required

Returns:

Type Description
ScoreArray

numpy.ndarray: Log-density values where lower scores correspond to potential anomalies.

Examples:

>>> detector = KDEDetector().fit(X_train)
>>> detector.score(X_test)[:3]
array([-3.2, -4.5, -2.8])

COPODDetector

Bases: _PyODAdapter

Copula-based Outlier Detector from PyOD.

FeatureBaggingDetector

Bases: _PyODAdapter

Feature Bagging ensemble from PyOD.

LODADetector

Bases: _PyODAdapter

Lightweight Online Detector of Anomalies from PyOD.

ABODDetector

Bases: _PyODAdapter

Angle-Based Outlier Detector from PyOD.

Modern tabular

anomalybench.analytics.detectors.modern_tabular

Modern tabular anomaly detectors with lightweight dependencies.

RandomNetworkDistillationDetector

Bases: BaseDetector

Random Network Distillation for tabular anomaly scoring.

A fixed random feature network defines a target representation. A compact predictor network is trained to reproduce that representation on training samples. High prediction error indicates inputs that do not match the learned normal structure.

RandomFeatureIsolationForestDetector

Bases: BaseDetector

Isolation Forest on random nonlinear tabular representations.

ECODDetector

Bases: BaseDetector

Empirical-CDF Outlier Detection from PyOD.

Graph

anomalybench.analytics.detectors.graph

Graph and network based anomaly detectors.

DegreeCentralityDetector

Bases: BaseDetector

Flag nodes with unusual degree centrality in a graph.

GraphIsolationForestDetector

Bases: BaseDetector

Apply Isolation Forest on basic graph structural features.

Forecasting

anomalybench.analytics.detectors.forecasting

Forecasting based anomaly detectors for time-series data.

ARIMADetector

Bases: BaseDetector

Detect anomalies using ARIMA forecast residuals.

ProphetDetector

Bases: BaseDetector

Use Prophet forecasting to score time-series anomalies.

Supporting modules

Preprocessing

anomalybench.analytics.preprocessing

Preprocessing utilities for anomaly detection workflows.

PreprocessingPipeline dataclass

Data preprocessing pipeline with sensible defaults.

The pipeline performs the following steps in order:

  1. Clip numeric features to configurable quantile bounds.
  2. Impute missing numeric values with the median and categorical values with the most frequent category.
  3. Scale numeric features using ~sklearn.preprocessing.StandardScaler.
  4. One-hot encode categorical features while ignoring unknown categories.
Parameters

clip_quantile : float, default=0.01 Lower quantile used to compute symmetric clipping bounds. Values must be in the half-open interval [0, 0.5). The upper bound is calculated as 1 - clip_quantile. A value of 0 disables clipping. numeric_impute_strategy : str, default="median" Strategy passed to ~sklearn.impute.SimpleImputer for numeric columns. categorical_impute_strategy : str, default="most_frequent" Strategy passed to ~sklearn.impute.SimpleImputer for categorical columns. one_hot_sparse : bool, default=False Whether the ~sklearn.preprocessing.OneHotEncoder should return a sparse matrix.

Notes

All intermediate estimators are stored so the same pipeline instance can be reused across training and inference datasets.

numeric_clip_bounds_ property

numeric_clip_bounds_: dict[str, tuple[float, float]] | None

Return the learned numeric clipping bounds if available.

fit

fit(data: DataFrame | ArrayLike) -> PreprocessingPipeline

Fit preprocessing steps on data.

transform

transform(data: DataFrame | ArrayLike) -> NDArray[np.float64]

Transform data using the fitted preprocessing steps.

fit_transform

fit_transform(data: DataFrame | ArrayLike) -> NDArray[np.float64]

Convenience method equivalent to calling fit then transform.

Time series

anomalybench.analytics.time_series

Shared time-series input and windowing contracts.

WindowSpec dataclass

Describe a deterministic rolling-window transformation.

WindowedScores

Bases: ndarray

Score array carrying point-label alignment for rolling windows.

coerce_sequence_batch

coerce_sequence_batch(data: DataFrame | Any, *, window_spec: WindowSpec | None = None) -> SequenceArray

Return data with shape (batch, sequence_length, channels).

Three-dimensional inputs are already interpreted as explicit batches of multivariate sequences. Two-dimensional inputs have two supported meanings:

  • without window_spec each row is a complete univariate sequence;
  • with window_spec rows are ordered time points and rolling windows are constructed across the first axis, preserving columns as channels.

window_start_indices

window_start_indices(n_points: int, spec: WindowSpec) -> NDArray[np.int_]

Return deterministic rolling-window start positions.

window_label_indices

window_label_indices(n_points: int, spec: WindowSpec) -> NDArray[np.int_]

Return point-label indices aligned to each produced window.

align_point_labels

align_point_labels(labels: Any, spec: WindowSpec) -> NDArray[Any]

Align point labels to rolling windows using the configured window end.

anomalybench.analytics.hyperparam

Hyperparameter search utilities for anomaly detectors.

grid_search(detector_name: str, param_grid: dict[str, Iterable], X, y, cv: int = 3)

Evaluate parameter combinations via stratified k-fold validation.

Parameters

detector_name: Registered detector identifier. param_grid: Mapping of parameter names to a list of candidate values. X, y: Feature matrix and ground-truth labels. X should support iloc indexing (e.g., pandas.DataFrame). cv: Number of cross-validation folds.

Returns

tuple[dict, float] Best parameter set and corresponding mean ROC-AUC score.

Scores are canonicalised to higher_is_more_anomalous before scoring, so detectors whose raw scores run the other way are ranked correctly.