Skip to main content

A Comprehensive and Scalable Python Library for Outlier Detection (Anomaly Detection)

Project description

Deployment & Documentation & Stats & License

PyPI version Anaconda version Documentation status GitHub stars GitHub forks Downloads Testing Coverage Status Maintainability License Benchmark


Read Me First

Welcome to PyOD, a well-developed and easy-to-use Python library for detecting anomalies in multivariate data. Whether you are working with a small-scale project or large datasets, PyOD provides a range of algorithms to fit your needs.

PyOD Version 2 is now available (Paper) [12], featuring:

  • Expanded Deep Learning Support: Integrates 12 modern neural models into a single PyTorch-based framework, bringing the total number of outlier detection methods to 45.

  • Enhanced Performance and Ease of Use: Models are optimized for efficiency and consistent performance across different datasets.

  • LLM-based Model Selection: Automated model selection guided by a large language model reduces manual tuning and assists users who may have limited experience with outlier detection.

  • Multi-Modal Detection via EmbeddingOD: Chain foundation model encoders (sentence-transformers, OpenAI, HuggingFace) with any PyOD detector for text and image anomaly detection. See EmbeddingOD example.

PyOD Ecosystem & Resources: NLP-ADBench (NLP anomaly detection) | TODS (time-series) | PyGOD (graph) | ADBench (benchmark) | AD-LLM (LLM-based AD) [50] | Resources


About PyOD

PyOD, established in 2017, has become a go-to Python library for detecting anomalous/outlying objects in multivariate data. This exciting yet challenging field is commonly referred to as Outlier Detection or Anomaly Detection.

PyOD includes more than 50 detection algorithms, from classical LOF (SIGMOD 2000) to the cutting-edge ECOD and DIF (TKDE 2022 and 2023). Since 2017, PyOD has been successfully used in numerous academic research projects and commercial products with more than 26 million downloads. It is also well acknowledged by the machine learning community with various dedicated posts/tutorials, including Analytics Vidhya, KDnuggets, and Towards Data Science.

PyOD is featured for:

  • Unified, User-Friendly Interface across various algorithms.

  • Wide Range of Models, from classic techniques to the latest deep learning methods in PyTorch.

  • High Performance & Efficiency, leveraging numba and joblib for JIT compilation and parallel processing.

  • Fast Training & Prediction, achieved through the SUOD framework [55].

Outlier Detection with 5 Lines of Code:

# Example: Training an ECOD detector
from pyod.models.ecod import ECOD
clf = ECOD()
clf.fit(X_train)
y_train_scores = clf.decision_scores_  # Outlier scores for training data
y_test_scores = clf.decision_function(X_test)  # Outlier scores for test data

Text Anomaly Detection with EmbeddingOD (pip install pyod sentence-transformers):

from pyod.models.embedding import EmbeddingOD
clf = EmbeddingOD(encoder='all-MiniLM-L6-v2', detector='KNN')
clf.fit(train_texts)                          # list of strings
scores = clf.decision_function(test_texts)    # anomaly scores
labels = clf.predict(test_texts)              # binary labels

# Or use a preset:
clf = EmbeddingOD.for_text(quality='fast')    # MiniLM + KNN

Image detection requires additional packages (pip install transformers torch). See EmbeddingOD example for details.

Selecting the Right Algorithm: Start with ECOD or Isolation Forest for tabular data, EmbeddingOD for text/image, or MetaOD for data-driven selection.

Citing PyOD:

If you use PyOD in a scientific publication, we would appreciate citations to the following paper(s):

PyOD 2: A Python Library for Outlier Detection with LLM-powered Model Selection is available as a preprint. If you use PyOD in a scientific publication, we would appreciate citations to the following paper:

@inproceedings{chen2025pyod,
  title={Pyod 2: A python library for outlier detection with llm-powered model selection},
  author={Chen, Sihan and Qian, Zhuangzhuang and Siu, Wingchun and Hu, Xingcan and Li, Jiaqi and Li, Shawn and Qin, Yuehan and Yang, Tiankai and Xiao, Zhuo and Ye, Wanghao and others},
  booktitle={Companion Proceedings of the ACM on Web Conference 2025},
  pages={2807--2810},
  year={2025}
}

PyOD paper is published in Journal of Machine Learning Research (JMLR) (MLOSS track).:

@article{zhao2019pyod,
    author  = {Zhao, Yue and Nasrullah, Zain and Li, Zheng},
    title   = {PyOD: A Python Toolbox for Scalable Outlier Detection},
    journal = {Journal of Machine Learning Research},
    year    = {2019},
    volume  = {20},
    number  = {96},
    pages   = {1-7},
    url     = {http://jmlr.org/papers/v20/19-011.html}
}

or:

Zhao, Y., Nasrullah, Z. and Li, Z., 2019. PyOD: A Python Toolbox for Scalable Outlier Detection. Journal of machine learning research (JMLR), 20(96), pp.1-7.

For a broader perspective on anomaly detection, see our NeurIPS papers on ADBench [17] and ADGym.

Table of Contents:


Installation

PyOD is designed for easy installation using either pip or conda. We recommend using the latest version of PyOD due to frequent updates and enhancements:

pip install pyod            # normal install
pip install --upgrade pyod  # or update if needed
conda install -c conda-forge pyod

Alternatively, you can clone and run the setup.py file:

git clone https://github.com/yzhao062/pyod.git
cd pyod
pip install .

Required Dependencies:

  • Python 3.8 or higher

  • joblib

  • matplotlib

  • numpy>=1.19

  • numba>=0.51

  • scipy>=1.5.1

  • scikit_learn>=0.22.0

Optional Dependencies (see details below):

  • combo (optional, required for models/combination.py and FeatureBagging)

  • pytorch (optional, required for AutoEncoder, and other deep learning models)

  • suod (optional, required for running SUOD model)

  • xgboost (optional, required for XGBOD)

  • pythresh (optional, required for thresholding)

  • sentence-transformers (optional, required for EmbeddingOD text detection)

  • openai (optional, required for EmbeddingOD with OpenAI embeddings)

  • transformers and torch (optional, required for EmbeddingOD image detection and HuggingFace encoder)


API Cheatsheet & Reference

The full API Reference is available at PyOD Documentation. Below is a quick cheatsheet for all detectors:

  • fit(X): Fit the detector. The parameter y is ignored in unsupervised methods.

  • decision_function(X): Predict raw anomaly scores for X using the fitted detector.

  • predict(X): Determine whether a sample is an outlier or not as binary labels using the fitted detector.

  • predict_proba(X): Estimate the probability of a sample being an outlier using the fitted detector.

  • predict_confidence(X): Assess the model’s confidence on a per-sample basis (applicable in predict and predict_proba) [38].

  • predict_with_rejection(X): Allow the detector to reject (i.e., abstain from making) highly uncertain predictions (output = -2) [39].

Key Attributes of a fitted model:

  • decision_scores_: Outlier scores of the training data. Higher scores typically indicate more abnormal behavior. Outliers usually have higher scores.

  • labels_: Binary labels of the training data, where 0 indicates inliers and 1 indicates outliers/anomalies.


ADBench Benchmark and Datasets

We just released a 45-page, the most comprehensive ADBench: Anomaly Detection Benchmark [17]. The fully open-sourced ADBench compares 30 anomaly detection algorithms on 57 benchmark datasets.

The organization of ADBench is provided below:

benchmark-fig

For a simpler visualization, we make the comparison of selected models via compare_all_models.py.

Comparison_of_All

Additional Topics


Implemented Algorithms

PyOD toolkit consists of four major functional groups:

(i) Individual Detection Algorithms :

Type

Abbr

Algorithm

Year

Ref

Probabilistic

ECOD

Unsupervised Outlier Detection Using Empirical Cumulative Distribution Functions

2022

[31]

Probabilistic

ABOD

Angle-Based Outlier Detection

2008

[24]

Probabilistic

FastABOD

Fast Angle-Based Outlier Detection using approximation

2008

[24]

Probabilistic

COPOD

COPOD: Copula-Based Outlier Detection

2020

[30]

Probabilistic

MAD

Median Absolute Deviation (MAD)

1993

[21]

Probabilistic

SOS

Stochastic Outlier Selection

2012

[22]

Probabilistic

QMCD

Quasi-Monte Carlo Discrepancy outlier detection

2001

[13]

Probabilistic

KDE

Outlier Detection with Kernel Density Functions

2007

[26]

Probabilistic

Sampling

Rapid distance-based outlier detection via sampling

2013

[46]

Probabilistic

GMM

Probabilistic Mixture Modeling for Outlier Analysis

[1] [Ch.2]

Linear Model

PCA

Principal Component Analysis (the sum of weighted projected distances to the eigenvector hyperplanes)

2003

[45]

Linear Model

KPCA

Kernel Principal Component Analysis

2007

[20]

Linear Model

MCD

Minimum Covariance Determinant (use the mahalanobis distances as the outlier scores)

1999

[18] [41]

Linear Model

CD

Use Cook’s distance for outlier detection

1977

[11]

Linear Model

OCSVM

One-Class Support Vector Machines

2001

[44]

Linear Model

LMDD

Deviation-based Outlier Detection (LMDD)

1996

[6]

Proximity-Based

LOF

Local Outlier Factor

2000

[8]

Proximity-Based

COF

Connectivity-Based Outlier Factor

2002

[47]

Proximity-Based

(Incremental) COF

Memory Efficient Connectivity-Based Outlier Factor (slower but reduce storage complexity)

2002

[47]

Proximity-Based

CBLOF

Clustering-Based Local Outlier Factor

2003

[19]

Proximity-Based

LOCI

LOCI: Fast outlier detection using the local correlation integral

2003

[36]

Proximity-Based

HBOS

Histogram-based Outlier Score

2012

[14]

Proximity-Based

HDBSCAN

Density-based clustering based on hierarchical density estimates

2013

[10]

Proximity-Based

kNN

k Nearest Neighbors (use the distance to the kth nearest neighbor as the outlier score)

2000

[40]

Proximity-Based

AvgKNN

Average kNN (use the average distance to k nearest neighbors as the outlier score)

2002

[5]

Proximity-Based

MedKNN

Median kNN (use the median distance to k nearest neighbors as the outlier score)

2002

[5]

Proximity-Based

SOD

Subspace Outlier Detection

2009

[25]

Proximity-Based

ROD

Rotation-based Outlier Detection

2020

[4]

Outlier Ensembles

IForest

Isolation Forest

2008

[32]

Outlier Ensembles

INNE

Isolation-based Anomaly Detection Using Nearest-Neighbor Ensembles

2018

[7]

Outlier Ensembles

DIF

Deep Isolation Forest for Anomaly Detection

2023

[49]

Outlier Ensembles

FB

Feature Bagging

2005

[27]

Outlier Ensembles

LSCP

LSCP: Locally Selective Combination of Parallel Outlier Ensembles

2019

[54]

Outlier Ensembles

XGBOD

Extreme Boosting Based Outlier Detection (Supervised)

2018

[53]

Outlier Ensembles

LODA

Lightweight On-line Detector of Anomalies

2016

[37]

Outlier Ensembles

SUOD

SUOD: Accelerating Large-scale Unsupervised Heterogeneous Outlier Detection (Acceleration)

2021

[55]

Neural Networks

AutoEncoder

Fully connected AutoEncoder (use reconstruction error as the outlier score)

[1] [Ch.3]

Neural Networks

VAE

Variational AutoEncoder (use reconstruction error as the outlier score)

2013

[23]

Neural Networks

Beta-VAE

Variational AutoEncoder (all customized loss term by varying gamma and capacity)

2018

[9]

Neural Networks

SO_GAAL

Single-Objective Generative Adversarial Active Learning

2019

[33]

Neural Networks

MO_GAAL

Multiple-Objective Generative Adversarial Active Learning

2019

[33]

Neural Networks

DeepSVDD

Deep One-Class Classification

2018

[42]

Neural Networks

AnoGAN

Anomaly Detection with Generative Adversarial Networks

2017

[43]

Neural Networks

ALAD

Adversarially learned anomaly detection

2018

[52]

Neural Networks

AE1SVM

Autoencoder-based One-class Support Vector Machine

2019

[34]

Neural Networks

DevNet

Deep Anomaly Detection with Deviation Networks

2019

[35]

Graph-based

R-Graph

Outlier detection by R-graph

2017

[51]

Graph-based

LUNAR

LUNAR: Unifying Local Outlier Detection Methods via Graph Neural Networks

2022

[15]

Embedding-based

EmbeddingOD

Multi-modal anomaly detection via foundation model embeddings (text, image)

2025

[28]

Ensemble methods (IForest, INNE, DIF, FB, LSCP, LODA, SUOD, XGBOD) are included in the table above. Score combination functions (average, maximization, AOM, MOA, median, majority vote) are in pyod.models.combination. See API docs for details.

(ii) Utility Functions:

Type

Name

Function

Data

generate_data

Synthesized data generation; normal data from multivariate Gaussian, outliers from uniform distribution

Data

generate_data_clusters

Synthesized data generation in clusters for more complex patterns

Evaluation

evaluate_print

Print ROC-AUC and Precision @ Rank n for a detector

Evaluation

precision_n_scores

Calculate Precision @ Rank n

Utility

get_label_n

Turn raw outlier scores into binary labels by assigning 1 to the top n scores

Stat

wpearsonr

Calculate the weighted Pearson correlation of two samples

Encoding

resolve_encoder

Resolve an encoder from a string name, BaseEncoder instance, or callable

Encoding

SentenceTransformerEncoder

Encode text via sentence-transformers models (e.g., MiniLM, mpnet)

Encoding

OpenAIEncoder

Encode text via OpenAI Embeddings API (text-embedding-3-small/large)

Encoding

HuggingFaceEncoder

Encode text or images via HuggingFace transformers (BERT, DINOv2, CLIP)


Quick Start for Outlier Detection

PyOD has been well acknowledged by the machine learning community with a few featured posts and tutorials.

Analytics Vidhya: An Awesome Tutorial to Learn Outlier Detection in Python using PyOD Library

KDnuggets: Intuitive Visualization of Outlier Detection Methods, An Overview of Outlier Detection Methods from PyOD

Towards Data Science: Anomaly Detection for Dummies

“examples/knn_example.py” demonstrates the basic API of using kNN detector. It is noted that the API across all other algorithms are consistent/similar.

More detailed instructions for running examples can be found in examples directory.

  1. Initialize a kNN detector, fit the model, and make the prediction.

    from pyod.models.knn import KNN   # kNN detector
    
    # train kNN detector
    clf_name = 'KNN'
    clf = KNN()
    clf.fit(X_train)
    
    # get the prediction label and outlier scores of the training data
    y_train_pred = clf.labels_  # binary labels (0: inliers, 1: outliers)
    y_train_scores = clf.decision_scores_  # raw outlier scores
    
    # get the prediction on the test data
    y_test_pred = clf.predict(X_test)  # outlier labels (0 or 1)
    y_test_scores = clf.decision_function(X_test)  # outlier scores
    
    # it is possible to get the prediction confidence as well
    y_test_pred, y_test_pred_confidence = clf.predict(X_test, return_confidence=True)  # outlier labels (0 or 1) and confidence in the range of [0,1]
  2. Evaluate the prediction by ROC and Precision @ Rank n (p@n).

    from pyod.utils.data import evaluate_print
    
    # evaluate and print the results
    print("\nOn Training Data:")
    evaluate_print(clf_name, y_train, y_train_scores)
    print("\nOn Test Data:")
    evaluate_print(clf_name, y_test, y_test_scores)
  3. See a sample output & visualization.

    On Training Data:
    KNN ROC:1.0, precision @ rank n:1.0
    
    On Test Data:
    KNN ROC:0.9989, precision @ rank n:0.9
    visualize(clf_name, X_train, y_train, X_test, y_test, y_train_pred,
        y_test_pred, show_figure=True, save_figure=False)

Visualization (knn_figure):

kNN example figure

Reference

Project details


Release history Release notifications | RSS feed

This version

2.1.0

Download files

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

Source Distribution

pyod-2.1.0.tar.gz (198.3 kB view details)

Uploaded Source

Built Distribution

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

pyod-2.1.0-py3-none-any.whl (238.4 kB view details)

Uploaded Python 3

File details

Details for the file pyod-2.1.0.tar.gz.

File metadata

  • Download URL: pyod-2.1.0.tar.gz
  • Upload date:
  • Size: 198.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for pyod-2.1.0.tar.gz
Algorithm Hash digest
SHA256 4f2f255b3f7f800ce542b4be97b2a1e810d2739afea98a0b3fb9588a7fdaf6f3
MD5 dd0a231a9c4286b035ae2c3f7247b710
BLAKE2b-256 0d5c109bbf7347b7f2b316629449cae927f9759675f86dd434d640419c032325

See more details on using hashes here.

File details

Details for the file pyod-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: pyod-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 238.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for pyod-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5ebabba5514a6df8863348ada0f33b9c8b4d0f09d04e834079739c15326cfd27
MD5 6b2ec3116aed37d54f42292b5a7bf0a5
BLAKE2b-256 b2c495da255d92291e0c979ebd3856901c0dc94f2e1af2e574a695f9925263d4

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 Pingdom Monitoring Sentry Error logging StatusPage Status page