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.
preprocessing_pipeline
property
¶
Return the currently configured preprocessing pipeline.
set_preprocessing_pipeline ¶
Attach a preprocessing pipeline used prior to model training.
fit_preprocessed ¶
Fit the detector after applying the preprocessing pipeline.
score_preprocessed ¶
Score data after applying the preprocessing pipeline.
detect_anomalies ¶
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 ¶
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 |
Examples:
>>> detector = IsolationForestDetector()
>>> _ = detector.fit(X_train)
>>> scores = detector.score(X_test)
>>> scores.shape
(len(X_test),)
fit ¶
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 |
required |
**params
|
Any
|
Additional keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
IsolationForestDetector |
IsolationForestDetector
|
The fitted detector instance. |
Examples:
score ¶
Compute anomaly scores for new observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: The isolation forest decision function values where |
ScoreArray
|
higher scores indicate more normal observations. |
Examples:
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 |
|
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 ¶
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
|
**params
|
Any
|
Additional parameters such as |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
LOFDetector |
LOFDetector
|
The fitted detector instance. |
Examples:
score ¶
Evaluate new observations using the trained LOF model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
A DataFrame shaped |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
list[float]: Negative local outlier factor values where larger values correspond to less anomalous points. |
Examples:
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 |
|
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 the SOS model on dense feature data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples of shape
|
required |
**params
|
Any
|
Optional SOS hyper-parameters such as |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
SOSDetector |
SOSDetector
|
The fitted detector instance. |
Examples:
score ¶
Score data using the fitted SOS model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to
score. If |
None
|
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative SOS probabilities where larger values indicate more anomalous observations. |
Examples:
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 |
|
sos |
Fitted |
|
hbos |
Fitted |
Examples:
>>> detector = EnsembleDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])
fit ¶
Train the constituent detectors and cache them for scoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training data matrix of
shape |
required |
**params
|
Any
|
Keyword arguments forwarded to each base detector. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
EnsembleDetector |
EnsembleDetector
|
The fitted ensemble instance. |
Examples:
score ¶
Combine component detector scores by normalized averaging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to be scored,
shaped |
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Aggregated anomaly scores where lower values imply more anomalous points. |
Examples:
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:
fit ¶
Estimate per-feature histograms with adaptive binning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples in a 2D
structure of shape |
required |
**params
|
Any
|
Additional configuration such as |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
HBOSDetector |
HBOSDetector
|
The fitted detector instance. |
Examples:
score ¶
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:
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 |
Examples:
fit ¶
Fit the nearest neighbor index on the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training matrix with
shape |
required |
**params
|
Any
|
Optional parameters, including |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
KNNDetector |
KNNDetector
|
The fitted detector instance. |
Examples:
score ¶
Score samples based on summed neighbor distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to evaluate with
shape |
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative summed distances, where smaller values indicate potential anomalies. |
Examples:
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 ¶
Train a one-class SVM on the input data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples with
shape |
required |
**params
|
Any
|
Keyword arguments for |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
OneClassSVMDetector |
OneClassSVMDetector
|
The fitted detector instance. |
Examples:
score ¶
Compute signed distance to the SVM decision boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to score with
shape |
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Decision function scores where larger values denote inliers. |
Examples:
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 |
Examples:
>>> detector = DBSCANDetector()
>>> _ = detector.fit(X_train, eps=0.5)
>>> detector.score(X_test)
array([...])
fit ¶
Cluster the training data using DBSCAN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Observations of shape
|
required |
**params
|
Any
|
Keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
DBSCANDetector |
DBSCANDetector
|
The fitted detector instance. |
Examples:
score ¶
Assign anomaly labels based on DBSCAN clustering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to cluster, shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Binary scores where |
Examples:
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 |
Examples:
>>> detector = EllipticEnvelopeDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])
fit ¶
Estimate a robust covariance model for Gaussian-like data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training matrix of shape
|
required |
**params
|
Any
|
Parameters to initialize
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
EllipticEnvelopeDetector |
EllipticEnvelopeDetector
|
The fitted detector instance. |
Examples:
score ¶
Compute distances to the robust covariance contour.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to score shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Decision function values where larger scores signify more typical observations. |
Examples:
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 |
Examples:
>>> detector = GaussianMixtureDetector()
>>> _ = detector.fit(X_train, n_components=3)
>>> detector.score(X_test)
array([...])
fit ¶
Fit a Gaussian mixture model to the training samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training data shaped
|
required |
**params
|
Any
|
Parameters passed to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
GaussianMixtureDetector |
GaussianMixtureDetector
|
The fitted detector instance. |
Examples:
score ¶
Return negative log-likelihood scores for the provided data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative log probabilities where larger values imply more anomalous points. |
Examples:
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 |
Examples:
>>> detector = SklearnLOFDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])
fit ¶
Train scikit-learn's LOF implementation in novelty mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples shaped
|
required |
**params
|
Any
|
Additional parameters for
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
SklearnLOFDetector |
SklearnLOFDetector
|
The fitted detector instance. |
Examples:
score ¶
Score samples using the LOF decision function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples for evaluation of
shape |
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Signed LOF scores where higher values indicate less anomalous observations. |
Examples:
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 |
Examples:
>>> detector = KMeansDetector()
>>> _ = detector.fit(X_train, n_clusters=5)
>>> detector.score(X_test)
array([...])
fit ¶
Train KMeans on the provided data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Observations shaped
|
required |
**params
|
Any
|
Optional KMeans parameters, such as |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
KMeansDetector |
KMeansDetector
|
The fitted detector instance. |
Examples:
score ¶
Score samples by their distance to the closest centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative minimum distances where lower values denote more anomalous points. |
Examples:
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 |
Examples:
>>> detector = PCAReconstructionDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])
fit ¶
Fit PCA to approximate the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples with
shape |
required |
**params
|
Any
|
Optional PCA parameters including |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
PCAReconstructionDetector |
PCAReconstructionDetector
|
The fitted detector instance. |
Examples:
score ¶
Compute negative reconstruction error for each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative L2 reconstruction errors where smaller values indicate more anomalous observations. |
Examples:
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 |
Examples:
>>> detector = MahalanobisDetector()
>>> _ = detector.fit(X_train)
>>> detector.score(X_test)
array([...])
fit ¶
Estimate the covariance matrix for Mahalanobis scoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training samples shaped
|
required |
**params
|
Any
|
Optional arguments passed to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
MahalanobisDetector |
MahalanobisDetector
|
The fitted detector instance. |
Examples:
score ¶
Compute negative Mahalanobis distance for each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to evaluate with
shape |
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Negative distances where smaller (more negative) values indicate greater anomaly likelihood. |
Examples:
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 |
Examples:
fit ¶
Fit a kernel density estimator to the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Training observations with
shape |
required |
**params
|
Any
|
Keyword arguments for
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
KDEDetector |
KDEDetector
|
The fitted detector instance. |
Examples:
score ¶
Evaluate log-density scores for the provided samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or ndarray
|
Samples to score shaped
|
required |
Returns:
| Type | Description |
|---|---|
ScoreArray
|
numpy.ndarray: Log-density values where lower scores correspond to potential anomalies. |
Examples:
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 ¶
ECODDetector ¶
Graph¶
anomalybench.analytics.detectors.graph ¶
Forecasting¶
anomalybench.analytics.detectors.forecasting ¶
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:
- Clip numeric features to configurable quantile bounds.
- Impute missing numeric values with the median and categorical values with the most frequent category.
- Scale numeric features using
~sklearn.preprocessing.StandardScaler. - 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.
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_speceach row is a complete univariate sequence; - with
window_specrows are ordered time points and rolling windows are constructed across the first axis, preserving columns as channels.
window_start_indices ¶
Return deterministic rolling-window start positions.
window_label_indices ¶
Return point-label indices aligned to each produced window.
align_point_labels ¶
Align point labels to rolling windows using the configured window end.
Hyperparameter search¶
anomalybench.analytics.hyperparam ¶
Hyperparameter search utilities for anomaly detectors.
grid_search ¶
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.