A Comprehensive and Scalable Python Library for Outlier Detection (Anomaly Detection)
Project description
Deployment & Documentation & Stats & License
Read Me First
Welcome to PyOD, a versatile Python library for detecting anomalies in multivariate data. Whether you’re tackling a smallscale project or large datasets, PyOD offers a range of algorithms to suit your needs.
For timeseries outlier detection, please use TODS.
For graph outlier detection, please use PyGOD.
Performance Comparison & Datasets: We have a 45page, the most comprehensive anomaly detection benchmark paper. The fully opensourced ADBench compares 30 anomaly detection algorithms on 57 benchmark datasets.
Learn more about anomaly detection @ Anomaly Detection Resources
PyOD on Distributed Systems: you could also run PyOD on databricks.
About PyOD
PyOD, established in 2017, has become a goto Python library for detecting anomalous/outlying objects in multivariate data. This exciting yet challenging field is commonly referred as Outlier Detection or Anomaly Detection.
PyOD includes more than 50 detection algorithms, from classical LOF (SIGMOD 2000) to the cuttingedge ECOD and DIF (TKDE 2022 and 2023). Since 2017, PyOD has been successfully used in numerous academic researches and commercial products with more than 17 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, UserFriendly Interface across various algorithms.
Wide Range of Models, from classic techniques to the latest deep learning methods.
High Performance & Efficiency, leveraging numba and joblib for JIT compilation and parallel processing.
Fast Training & Prediction, achieved through the SUOD framework [48].
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
Selecting the Right Algorithm:. Unsure where to start? Consider these robust and interpretable options:
ECOD: Example of using ECOD for outlier detection
Isolation Forest: Example of using Isolation Forest for outlier detection
Alternatively, explore MetaOD for a datadriven approach.
Citing PyOD:
PyOD paper is published in Journal of Machine Learning Research (JMLR) (MLOSS track). If you use PyOD in a scientific publication, we would appreciate citations to the following paper:
@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 = {17}, url = {http://jmlr.org/papers/v20/19011.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.17.
For a broader perspective on anomaly detection, see our NeurIPS papers ADBench: Anomaly Detection Benchmark Paper & ADGym: Design Choices for Deep Anomaly Detection:
@article{han2022adbench, title={Adbench: Anomaly detection benchmark}, author={Han, Songqiao and Hu, Xiyang and Huang, Hailiang and Jiang, Minqi and Zhao, Yue}, journal={Advances in Neural Information Processing Systems}, volume={35}, pages={3214232159}, year={2022} } @article{jiang2023adgym, title={ADGym: Design Choices for Deep Anomaly Detection}, author={Jiang, Minqi and Hou, Chaochuan and Zheng, Ao and Han, Songqiao and Huang, Hailiang and Wen, Qingsong and Hu, Xiyang and Zhao, Yue}, journal={Advances in Neural Information Processing Systems}, volume={36}, year={2023} }
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 condaforge pyod
Alternatively, you could clone and run setup.py file:
git clone https://github.com/yzhao062/pyod.git
cd pyod
pip install .
Required Dependencies:
Python 3.6 or higher
joblib
matplotlib
numpy>=1.19
numba>=0.51
scipy>=1.5.1
scikit_learn>=0.22.0
six
Optional Dependencies (see details below):
combo (optional, required for models/combination.py and FeatureBagging)
keras/tensorflow (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)
Warning: PyOD includes several neural networkbased models, such as AutoEncoders, implemented in Tensorflow and PyTorch. These deep learning libraries are not automatically installed by PyOD to avoid conflicts with existing installations. If you plan to use neuralnet based models, please ensure these libraries are installed. See the neuralnet FAQ for guidance. Additionally, xgboost is not installed by default but is required for models like XGBOD.
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 persample basis (applicable in predict and predict_proba) [33].
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 45page, the most comprehensive ADBench: Anomaly Detection Benchmark [15]. The fully opensourced ADBench compares 30 anomaly detection algorithms on 57 benchmark datasets.
The organization of ADBench is provided below:
For a simpler visualization, we make the comparison of selected models via compare_all_models.py.
Model Save & Load
PyOD takes a similar approach of sklearn regarding model persistence. See model persistence for clarification.
In short, we recommend to use joblib or pickle for saving and loading PyOD models. See “examples/save_load_model_example.py” for an example. In short, it is simple as below:
from joblib import dump, load
# save the model
dump(clf, 'clf.joblib')
# load the model
clf = load('clf.joblib')
It is known that there are challenges in saving neural network models. Check #328 and #88 for temporary workaround.
Fast Train with SUOD
Fast training and prediction: it is possible to train and predict with a large number of detection models in PyOD by leveraging SUOD framework [48]. See SUOD Paper and SUOD example.
from pyod.models.suod import SUOD
# initialized a group of outlier detectors for acceleration
detector_list = [LOF(n_neighbors=15), LOF(n_neighbors=20),
LOF(n_neighbors=25), LOF(n_neighbors=35),
COPOD(), IForest(n_estimators=100),
IForest(n_estimators=200)]
# decide the number of parallel process, and the combination method
# then clf can be used as any outlier detection model
clf = SUOD(base_estimators=detector_list, n_jobs=2, combination='average',
verbose=False)
Thresholding Outlier Scores
A more data based approach can be taken when setting the contamination level. By using a thresholding method, guessing an abritrary value can be replaced with tested techniques for seperating inliers and outliers. Refer to PyThresh for a more in depth look at thresholding.
from pyod.models.knn import KNN
from pyod.models.thresholds import FILTER
# Set the outlier detection and thresholding methods
clf = KNN(contamination=FILTER())
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 

Probabilistic 
ABOD 
AngleBased Outlier Detection 
2008 

Probabilistic 
FastABOD 
Fast AngleBased Outlier Detection using approximation 
2008 

Probabilistic 
COPOD 
COPOD: CopulaBased Outlier Detection 
2020 

Probabilistic 
MAD 
Median Absolute Deviation (MAD) 
1993 

Probabilistic 
SOS 
Stochastic Outlier Selection 
2012 

Probabilistic 
QMCD 
QuasiMonte Carlo Discrepancy outlier detection 
2001 

Probabilistic 
KDE 
Outlier Detection with Kernel Density Functions 
2007 

Probabilistic 
Sampling 
Rapid distancebased outlier detection via sampling 
2013 

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 

Linear Model 
KPCA 
Kernel Principal Component Analysis 
2007 

Linear Model 
MCD 
Minimum Covariance Determinant (use the mahalanobis distances as the outlier scores) 
1999 

Linear Model 
CD 
Use Cook’s distance for outlier detection 
1977 

Linear Model 
OCSVM 
OneClass Support Vector Machines 
2001 

Linear Model 
LMDD 
Deviationbased Outlier Detection (LMDD) 
1996 

ProximityBased 
LOF 
Local Outlier Factor 
2000 

ProximityBased 
COF 
ConnectivityBased Outlier Factor 
2002 

ProximityBased 
(Incremental) COF 
Memory Efficient ConnectivityBased Outlier Factor (slower but reduce storage complexity) 
2002 

ProximityBased 
CBLOF 
ClusteringBased Local Outlier Factor 
2003 

ProximityBased 
LOCI 
LOCI: Fast outlier detection using the local correlation integral 
2003 

ProximityBased 
HBOS 
Histogrambased Outlier Score 
2012 

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

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

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

ProximityBased 
SOD 
Subspace Outlier Detection 
2009 

ProximityBased 
ROD 
Rotationbased Outlier Detection 
2020 

Outlier Ensembles 
IForest 
Isolation Forest 
2008 

Outlier Ensembles 
INNE 
Isolationbased Anomaly Detection Using NearestNeighbor Ensembles 
2018 

Outlier Ensembles 
DIF 
Deep Isolation Forest for Anomaly Detection 
2023 

Outlier Ensembles 
FB 
Feature Bagging 
2005 

Outlier Ensembles 
LSCP 
LSCP: Locally Selective Combination of Parallel Outlier Ensembles 
2019 

Outlier Ensembles 
XGBOD 
Extreme Boosting Based Outlier Detection (Supervised) 
2018 

Outlier Ensembles 
LODA 
Lightweight Online Detector of Anomalies 
2016 

Outlier Ensembles 
SUOD 
SUOD: Accelerating Largescale Unsupervised Heterogeneous Outlier Detection (Acceleration) 
2021 

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 

Neural Networks 
BetaVAE 
Variational AutoEncoder (all customized loss term by varying gamma and capacity) 
2018 

Neural Networks 
SO_GAAL 
SingleObjective Generative Adversarial Active Learning 
2019 

Neural Networks 
MO_GAAL 
MultipleObjective Generative Adversarial Active Learning 
2019 

Neural Networks 
DeepSVDD 
Deep OneClass Classification 
2018 

Neural Networks 
AnoGAN 
Anomaly Detection with Generative Adversarial Networks 
2017 

Neural Networks 
ALAD 
Adversarially learned anomaly detection 
2018 

Graphbased 
RGraph 
Outlier detection by Rgraph 
2017 

Graphbased 
LUNAR 
LUNAR: Unifying Local Outlier Detection Methods via Graph Neural Networks 
2022 
(ii) Outlier Ensembles & Outlier Detector Combination Frameworks:
Type 
Abbr 
Algorithm 
Year 
Ref 

Outlier Ensembles 
FB 
Feature Bagging 
2005 

Outlier Ensembles 
LSCP 
LSCP: Locally Selective Combination of Parallel Outlier Ensembles 
2019 

Outlier Ensembles 
XGBOD 
Extreme Boosting Based Outlier Detection (Supervised) 
2018 

Outlier Ensembles 
LODA 
Lightweight Online Detector of Anomalies 
2016 

Outlier Ensembles 
SUOD 
SUOD: Accelerating Largescale Unsupervised Heterogeneous Outlier Detection (Acceleration) 
2021 

Outlier Ensembles 
INNE 
Isolationbased Anomaly Detection Using NearestNeighbor Ensembles 
2018 

Combination 
Average 
Simple combination by averaging the scores 
2015 

Combination 
Weighted Average 
Simple combination by averaging the scores with detector weights 
2015 

Combination 
Maximization 
Simple combination by taking the maximum scores 
2015 

Combination 
AOM 
Average of Maximum 
2015 

Combination 
MOA 
Maximization of Average 
2015 

Combination 
Median 
Simple combination by taking the median of the scores 
2015 

Combination 
majority Vote 
Simple combination by taking the majority vote of the labels (weights can be used) 
2015 
(iii) Outlier Detection Score Thresholding Methods:
Type 
Abbr 
Algorithm 
Documentation 

KernelBased 
AUCP 
Area Under Curve Percentage 

Statistical MomentBased 
BOOT 
Bootstrapping 

NormalityBased 
CHAU 
Chauvenet’s Criterion 

Linear Model 
CLF 
Trained Linear Classifier 

clusterBased 
CLUST 
Clustering Based 

KernelBased 
CPD 
Change Point Detection 

TransformationBased 
DECOMP 
Decomposition 

NormalityBased 
DSN 
Distance Shift from Normal 

CurveBased 
EB 
Elliptical Boundary 

KernelBased 
FGD 
Fixed Gradient Descent 

FilterBased 
FILTER 
Filtering Based 

CurveBased 
FWFM 
Full Width at Full Minimum 

Statistical TestBased 
GESD 
Generalized Extreme Studentized Deviate 

FilterBased 
HIST 
Histogram Based 

QuantileBased 
IQR 
InterQuartile Region 

Statistical MomentBased 
KARCH 
Karcher mean (Riemannian Center of Mass) 

Statistical MomentBased 
MAD 
Median Absolute Deviation 

Statistical TestBased 
MCST 
Monte Carlo Shapiro Tests 

EnsemblesBased 
META 
Metamodel Trained Classifier 

TransformationBased 
MOLL 
Friedrichs’ Mollifier 

Statistical TestBased 
MTT 
Modified Thompson Tau Test 

Linear Model 
OCSVM 
OneClass Support Vector Machine 

QuantileBased 
QMCD 
QuasiMonte Carlo Discrepancy 

Linear Model 
REGR 
Regression Based 

Neural Networks 
VAE 
Variational Autoencoder 

CurveBased 
WIND 
Topological Winding Number 

TransformationBased 
YJ 
YeoJohnson Transformation 

NormalityBased 
ZSCORE 
Zscore 
(iV) Utility Functions:
Type 
Name 
Function 
Documentation 

Data 
generate_data 
Synthesized data generation; normal data is generated by a multivariate Gaussian and outliers are generated by a uniform distribution 

Data 
generate_data_clusters 
Synthesized data generation in clusters; more complex data patterns can be created with multiple clusters 

Stat 
wpearsonr 
Calculate the weighted Pearson correlation of two samples 

Utility 
get_label_n 
Turn raw outlier scores into binary labels by assign 1 to top n outlier scores 

Utility 
precision_n_scores 
calculate precision @ rank n 
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
Computer Vision News (March 2019): Python Open Source Toolbox for Outlier Detection
“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.
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]
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)
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):
How to Contribute
You are welcome to contribute to this exciting project:
Please first check Issue lists for “help wanted” tag and comment the one you are interested. We will assign the issue to you.
Fork the master branch and add your improvement/modification/fix.
Create a pull request to development branch and follow the pull request template PR template
Automatic tests will be triggered. Make sure all tests are passed. Please make sure all added modules are accompanied with proper test functions.
To make sure the code has the same style and standard, please refer to abod.py, hbos.py, or feature_bagging.py for example.
You are also welcome to share your ideas by opening an issue or dropping me an email at zhaoy@cmu.edu :)
Inclusion Criteria
Similarly to scikitlearn, We mainly consider wellestablished algorithms for inclusion. A rule of thumb is at least two years since publication, 50+ citations, and usefulness.
However, we encourage the author(s) of newly proposed models to share and add your implementation into PyOD for boosting ML accessibility and reproducibility. This exception only applies if you could commit to the maintenance of your model for at least two year period.
Reference
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.