For time-series outlier detection, please use TODS.
For graph outlier detection, please use PyGOD.
PyOD is the most comprehensive and scalable Python library for detecting outlying objects in
multivariate data. This exciting yet challenging field is commonly referred as
Outlier Detection
or Anomaly Detection.
PyOD includes more than 40 detection algorithms, from classical LOF (SIGMOD 2000) to
the latest ECOD (TKDE 2022). Since 2017, PyOD has been successfully used in numerous academic researches and
commercial products with more than 10 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 APIs, detailed documentation, and interactive examples across various algorithms.
Advanced models, including classical distance and density estimation, latest deep learning methods, and emerging algorithms like ECOD.
Optimized performance with JIT and parallelization using numba and joblib.
# train an ECOD detectorfrompyod.models.ecodimportECODclf=ECOD()
clf.fit(X_train)
# get outlier scoresy_train_scores=clf.decision_scores_# raw outlier scores on the train datay_test_scores=clf.decision_function(X_test) # predict raw outlier scores on test
Personal suggestion on selecting an OD algorithm. If you do not know which algorithm to try, go with:
@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.
If you want more general insights of anomaly detection and/or algorithm performance comparison, please see our
NeurIPS 2022 paper ADBench: Anomaly Detection Benchmark Paper:
@inproceedings{han2022adbench,
title={ADBench: Anomaly Detection Benchmark},
author={Songqiao Han and Xiyang Hu and Hailiang Huang and Mingqi Jiang and Yue Zhao},
booktitle={Neural Information Processing Systems (NeurIPS)}
year={2022},
}
It is recommended to use pip or conda for installation. Please make sure
the latest version is installed, as PyOD is updated frequently:
pip install pyod # normal install
pip install --upgrade pyod # or update if needed
conda install -c conda-forge 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+
joblib
matplotlib
numpy>=1.19
numba>=0.51
scipy>=1.5.1
scikit_learn>=0.20.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)
pandas (optional, required for running benchmark)
suod (optional, required for running SUOD model)
xgboost (optional, required for XGBOD)
pythresh to use thresholding
Warning:
PyOD has multiple neural network based models, e.g., AutoEncoders, which are
implemented in both Tensorflow and PyTorch. However, PyOD does NOT install these deep learning libraries for you.
This reduces the risk of interfering with your local copies.
If you want to use neural-net based models, please make sure these deep learning libraries are installed.
Instructions are provided: neural-net FAQ.
Similarly, models depending on xgboost, e.g., XGBOD, would NOT enforce xgboost installation by default.
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:
fromjoblibimportdump, load# save the modeldump(clf, 'clf.joblib')
# load the modelclf=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 [47].
See SUOD Paper
and SUOD example.
frompyod.models.suodimportSUOD# initialized a group of outlier detectors for accelerationdetector_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 modelclf=SUOD(base_estimators=detector_list, n_jobs=2, combination='average',
verbose=False)
Implemented Algorithms
PyOD toolkit consists of three major functional groups:
(i) Individual Detection Algorithms :
Type
Abbr
Algorithm
Year
Ref
Probabilistic
ECOD
Unsupervised Outlier Detection Using Empirical Cumulative Distribution Functions
"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.
frompyod.models.knnimportKNN# kNN detector# train kNN detectorclf_name='KNN'clf=KNN()
clf.fit(X_train)
# get the prediction label and outlier scores of the training datay_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 datay_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 welly_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).
frompyod.utils.dataimportevaluate_print# evaluate and print the resultsprint("\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)
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 [email protected] :)
Inclusion Criteria
Similarly to scikit-learn,
We mainly consider well-established 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
[1]
(1, 2) Aggarwal, C.C., 2015. Outlier analysis. In Data mining (pp. 237-263). Springer, Cham.
[2]
(1, 2, 3, 4, 5, 6, 7) Aggarwal, C.C. and Sathe, S., 2015. Theoretical foundations and algorithms for outlier ensembles.ACM SIGKDD Explorations Newsletter, 17(1), pp.24-47.
[3]
Aggarwal, C.C. and Sathe, S., 2017. Outlier ensembles: An introduction. Springer.
Almardeny, Y., Boujnah, N. and Cleary, F., 2020. A Novel Outlier Detection Method for Multivariate Data. IEEE Transactions on Knowledge and Data Engineering.
[5]
(1, 2) Angiulli, F. and Pizzuti, C., 2002, August. Fast outlier detection in high dimensional spaces. In European Conference on Principles of Data Mining and Knowledge Discovery pp. 15-27.
Arning, A., Agrawal, R. and Raghavan, P., 1996, August. A Linear Method for Deviation Detection in Large Databases. In KDD (Vol. 1141, No. 50, pp. 972-981).
[7]
(1, 2) Bandaragoda, T. R., Ting, K. M., Albrecht, D., Liu, F. T., Zhu, Y., and Wells, J. R., 2018, Isolation-based anomaly detection using nearest-neighbor ensembles. Computational Intelligence, 34(4), pp. 968-998.
Fang, K.T. and Ma, C.X., 2001. Wrap-around L2-discrepancy of random sampling, Latin hypercube and uniform designs. Journal of complexity, 17(4), pp.608-624.
Goldstein, M. and Dengel, A., 2012. Histogram-based outlier score (hbos): A fast unsupervised anomaly detection algorithm. In KI-2012: Poster and Demo Track, pp.59-63.
Goodge, A., Hooi, B., Ng, S.K. and Ng, W.S., 2022, June. Lunar: Unifying local outlier detection methods via graph neural networks. In Proceedings of the AAAI Conference on Artificial Intelligence.
[14]
Gopalan, P., Sharan, V. and Wieder, U., 2019. PIDForest: Anomaly Detection via Partial Identification. In Advances in Neural Information Processing Systems, pp. 15783-15793.
Hardin, J. and Rocke, D.M., 2004. Outlier detection in the multiple cluster setting using the minimum covariance determinant estimator. Computational Statistics & Data Analysis, 44(4), pp.625-638.
Janssens, J.H.M., Huszár, F., Postma, E.O. and van den Herik, H.J., 2012. Stochastic outlier selection. Technical report TiCC TR 2012-001, Tilburg University, Tilburg Center for Cognition and Communication, Tilburg, The Netherlands.
Kriegel, H.P., Kröger, P., Schubert, E. and Zimek, A., 2009, April. Outlier detection in axis-parallel subspaces of high dimensional data. In Pacific-Asia Conference on Knowledge Discovery and Data Mining, pp. 831-838. Springer, Berlin, Heidelberg.
Latecki, L.J., Lazarevic, A. and Pokrajac, D., 2007, July. Outlier detection with kernel density functions. In International Workshop on Machine Learning and Data Mining in Pattern Recognition (pp. 61-75). Springer, Berlin, Heidelberg.
[25]
(1, 2) Lazarevic, A. and Kumar, V., 2005, August. Feature bagging for outlier detection. In KDD '05. 2005.
[26]
Li, D., Chen, D., Jin, B., Shi, L., Goh, J. and Ng, S.K., 2019, September. MAD-GAN: Multivariate anomaly detection for time series data with generative adversarial networks. In International Conference on Artificial Neural Networks (pp. 703-716). Springer, Cham.
Li, Z., Zhao, Y., Hu, X., Botta, N., Ionescu, C. and Chen, H. G. ECOD: Unsupervised Outlier Detection Using Empirical Cumulative Distribution Functions. IEEE Transactions on Knowledge and Data Engineering (TKDE), 2022.
Liu, F.T., Ting, K.M. and Zhou, Z.H., 2008, December. Isolation forest. In International Conference on Data Mining, pp. 413-422. IEEE.
[30]
(1, 2) Liu, Y., Li, Z., Zhou, C., Jiang, Y., Sun, J., Wang, M. and He, X., 2019. Generative adversarial active learning for unsupervised outlier detection. IEEE Transactions on Knowledge and Data Engineering.
Papadimitriou, S., Kitagawa, H., Gibbons, P.B. and Faloutsos, C., 2003, March. LOCI: Fast outlier detection using the local correlation integral. In ICDE '03, pp. 315-326. IEEE.
Perini, L., Vercruyssen, V., Davis, J. Quantifying the confidence of anomaly detectors in their example-wise predictions. In Joint European Conference on Machine Learning and Knowledge Discovery in Databases (ECML-PKDD), 2020.
Ramaswamy, S., Rastogi, R. and Shim, K., 2000, May. Efficient algorithms for mining outliers from large data sets. ACM Sigmod Record, 29(2), pp. 427-438.
Ruff, L., Vandermeulen, R., Goernitz, N., Deecke, L., Siddiqui, S.A., Binder, A., Müller, E. and Kloft, M., 2018, July. Deep one-class classification. In International conference on machine learning (pp. 4393-4402). PMLR.
Schlegl, T., Seeböck, P., Waldstein, S.M., Schmidt-Erfurth, U. and Langs, G., 2017, June. Unsupervised anomaly detection with generative adversarial networks to guide marker discovery. In International conference on information processing in medical imaging (pp. 146-157). Springer, Cham.
Scholkopf, B., Platt, J.C., Shawe-Taylor, J., Smola, A.J. and Williamson, R.C., 2001. Estimating the support of a high-dimensional distribution. Neural Computation, 13(7), pp.1443-1471.
Shyu, M.L., Chen, S.C., Sarinnapakorn, K. and Chang, L., 2003. A novel anomaly detection scheme based on principal component classifier. MIAMI UNIV CORAL GABLES FL DEPT OF ELECTRICAL AND COMPUTER ENGINEERING.
Sugiyama, M. and Borgwardt, K., 2013. Rapid distance-based outlier detection via sampling. Advances in neural information processing systems, 26.
[41]
(1, 2) Tang, J., Chen, Z., Fu, A.W.C. and Cheung, D.W., 2002, May. Enhancing effectiveness of outlier detections for low density patterns. In Pacific-Asia Conference on Knowledge Discovery and Data Mining, pp. 535-548. Springer, Berlin, Heidelberg.
[42]
Wang, X., Du, Y., Lin, S., Cui, P., Shen, Y. and Yang, Y., 2019. adVAE: A self-adversarial variational autoencoder with Gaussian anomaly prior knowledge for anomaly detection. Knowledge-Based Systems.
You, C., Robinson, D.P. and Vidal, R., 2017. Provable self-representation based outlier detection in a union of subspaces. In Proceedings of the IEEE conference on computer vision and pattern recognition.
Zenati, H., Romain, M., Foo, C.S., Lecouat, B. and Chandrasekhar, V., 2018, November. Adversarially learned anomaly detection. In 2018 IEEE International conference on data mining (ICDM) (pp. 727-736). IEEE.
[45]
(1, 2) Zhao, Y. and Hryniewicki, M.K. XGBOD: Improving Supervised Outlier Detection with Unsupervised Representation Learning. IEEE International Joint Conference on Neural Networks, 2018.
[46]
(1, 2) Zhao, Y., Nasrullah, Z., Hryniewicki, M.K. and Li, Z., 2019, May. LSCP: Locally selective combination in parallel outlier ensembles. In Proceedings of the 2019 SIAM International Conference on Data Mining (SDM), pp. 585-593. Society for Industrial and Applied Mathematics.
[47]
(1, 2, 3, 4) Zhao, Y., Hu, X., Cheng, C., Wang, C., Wan, C., Wang, W., Yang, J., Bai, H., Li, Z., Xiao, C., Wang, Y., Qiao, Z., Sun, J. and Akoglu, L. (2021). SUOD: Accelerating Large-scale Unsupervised Heterogeneous Outlier Detection. Conference on Machine Learning and Systems (MLSys).