pyod
PyOD 是一款功能强大且易于上手的 Python 开源库,专门用于在表格、文本及图像数据中识别异常值与离群点。它有效解决了用户在处理多维数据时,难以从海量信息中快速定位罕见模式、欺诈行为或系统故障等关键问题的挑战。
无论是从事数据科学开发的工程师、进行算法研究的研究人员,还是希望提升数据质量的分析专家,都能通过 PyOD 高效完成异常检测任务。该库自 2017 年发布以来已发展成为行业标杆,其最新的 V2 版本更是带来了显著的技术突破:不仅将支持的检测算法扩展至 45 种,还深度集成了 12 种基于 PyTorch 的现代深度学习模型。
PyOD 的独特亮点在于引入了大语言模型(LLM)辅助的自动模型选择功能,大幅降低了人工调参门槛,让经验有限的用户也能轻松上手。此外,通过 EmbeddingOD 模块,它能灵活结合基础模型编码器,实现对非结构化文本和图像的多模态异常检测。凭借丰富的算法库、优化的性能表现以及完善的文档支持,PyOD 是构建可靠异常检测系统的理想选择。
使用场景
某电商风控团队每天需从百万级订单数据中识别刷单、盗号等异常行为,传统规则引擎已难以应对日益复杂的欺诈模式。
没有 pyod 时
- 算法选型困难:面对孤立森林、LOF 等多种检测算法,缺乏统一接口,每次尝试新模型都需重写大量代码。
- 多模态数据束手无策:仅能处理结构化表格数据,对于包含用户评论文本或商品图片的混合数据,无法有效提取特征进行联合异常判断。
- 调参成本高昂:依赖人工经验反复调整阈值和参数,耗时数天且容易因主观判断导致漏报或误报。
- 深度学习门槛高:想引入先进的神经网络模型提升准确率,但缺乏现成的 PyTorch 集成框架,自行实现难度极大。
使用 pyod 后
- 一键切换模型:通过统一的 API 接口,可在 45 种内置算法(含 12 种深度学习方法)间自由切换,快速验证哪种模型最适合当前数据分布。
- 轻松搞定多模态:利用 EmbeddingOD 模块,直接调用预训练模型将文本和图片转化为向量,无缝衔接检测器,实现全维度风险扫描。
- 智能自动调优:借助 LLM 驱动的模型选择功能,自动推荐最优算法与参数组合,将原本数天的调优过程缩短至小时级。
- 性能效率双升:底层优化的计算框架显著提升了大规模数据集的处理速度,同时保持了高准确率,让实时风控成为可能。
pyod 将复杂的异常检测技术封装为简单易用的工具,让团队能以最低成本构建高精度的多模态智能风控系统。
运行环境要求
- 未说明
- 非必需
- 仅在使用可选的深度学习模型(如 AutoEncoder)或 EmbeddingOD 进行图像/文本检测时需要 PyTorch,具体显卡型号、显存及 CUDA 版本未在文档中明确指定
未说明

快速开始
Python Outlier Detection (PyOD) V2
Deployment & Documentation & Stats & License
|badge_pypi| |badge_anaconda| |badge_docs| |badge_stars| |badge_forks| |badge_downloads| |badge_testing| |badge_coverage| |badge_maintainability| |badge_license| |badge_benchmark|
.. |badge_pypi| image:: https://img.shields.io/pypi/v/pyod.svg?color=brightgreen :target: https://pypi.org/project/pyod/ :alt: PyPI version
.. |badge_anaconda| image:: https://anaconda.org/conda-forge/pyod/badges/version.svg :target: https://anaconda.org/conda-forge/pyod :alt: Anaconda version
.. |badge_docs| image:: https://readthedocs.org/projects/pyod/badge/?version=latest :target: https://pyod.readthedocs.io/en/latest/?badge=latest :alt: Documentation status
.. |badge_stars| image:: https://img.shields.io/github/stars/yzhao062/pyod.svg :target: https://github.com/yzhao062/pyod/stargazers :alt: GitHub stars
.. |badge_forks| image:: https://img.shields.io/github/forks/yzhao062/pyod.svg?color=blue :target: https://github.com/yzhao062/pyod/network :alt: GitHub forks
.. |badge_downloads| image:: https://pepy.tech/badge/pyod :target: https://pepy.tech/project/pyod :alt: Downloads
.. |badge_testing| image:: https://github.com/yzhao062/pyod/actions/workflows/testing.yml/badge.svg :target: https://github.com/yzhao062/pyod/actions/workflows/testing.yml :alt: Testing
.. |badge_coverage| image:: https://coveralls.io/repos/github/yzhao062/pyod/badge.svg :target: https://coveralls.io/github/yzhao062/pyod :alt: Coverage Status
.. |badge_maintainability| image:: https://api.codeclimate.com/v1/badges/bdc3d8d0454274c753c4/maintainability :target: https://codeclimate.com/github/yzhao062/Pyod/maintainability :alt: Maintainability
.. |badge_license| image:: https://img.shields.io/github/license/yzhao062/pyod.svg :target: https://github.com/yzhao062/pyod/blob/master/LICENSE :alt: License
.. |badge_benchmark| image:: https://img.shields.io/badge/ADBench-benchmark_results-pink :target: https://github.com/Minqi824/ADBench :alt: 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 <https://www.arxiv.org/abs/2412.12154>) [#Chen2024PyOD], 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 <https://github.com/yzhao062/pyod/blob/master/examples/embedding_od_example.py>_.
PyOD Ecosystem & Resources:
NLP-ADBench <https://github.com/USC-FORTIS/NLP-ADBench>_ (NLP anomaly detection) | TODS <https://github.com/datamllab/tods>_ (time-series) | PyGOD <https://pygod.org/>_ (graph) | ADBench <https://github.com/Minqi824/ADBench>_ (benchmark) | AD-LLM <https://arxiv.org/abs/2412.11142>_ (LLM-based AD) [#Yang2024ad]_ | Resources <https://github.com/yzhao062/anomaly-detection-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 <https://en.wikipedia.org/wiki/Anomaly_detection>_ or Anomaly Detection <https://en.wikipedia.org/wiki/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 <https://pepy.tech/project/pyod>. It is also well acknowledged by the machine learning community with various dedicated posts/tutorials, including Analytics Vidhya <https://www.analyticsvidhya.com/blog/2019/02/outlier-detection-python-pyod/>, KDnuggets <https://www.kdnuggets.com/2019/02/outlier-detection-methods-cheat-sheet.html>, and Towards Data Science <https://towardsdatascience.com/anomaly-detection-for-dummies-15f148e559c1>.
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 <https://github.com/numba/numba>_ andjoblib <https://github.com/joblib/joblib>_ for JIT compilation and parallel processing. - Fast Training & Prediction, achieved through the SUOD framework [#Zhao2021SUOD]_.
Outlier Detection with 5 Lines of Code:
.. code-block:: python
# 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):
.. code-block:: python
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 <https://github.com/yzhao062/pyod/blob/master/examples/embedding_od_example.py>_ for details.
Selecting the Right Algorithm: Start with ECOD <https://github.com/yzhao062/pyod/blob/master/examples/ecod_example.py>_ or Isolation Forest <https://github.com/yzhao062/pyod/blob/master/examples/iforest_example.py>_ for tabular data, EmbeddingOD <https://github.com/yzhao062/pyod/blob/master/examples/embedding_od_example.py>_ for text/image, or MetaOD <https://github.com/yzhao062/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 <https://arxiv.org/abs/2412.12154>_ 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 <http://www.jmlr.org/papers/volume20/19-011/19-011.pdf>_ is published in Journal of Machine Learning Research (JMLR) <http://www.jmlr.org/>_ (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 <https://arxiv.org/abs/2206.09426>_ [#Han2022ADBench]_ and ADGym <https://arxiv.org/abs/2309.15376>_.
Table of Contents:
Installation <#installation>_API Cheatsheet & Reference <#api-cheatsheet--reference>_ADBench Benchmark and Datasets <#adbench-benchmark-and-datasets>_Additional Topics <#additional-topics>_ (Model Save/Load, SUOD, Thresholding)Implemented Algorithms <#implemented-algorithms>_Quick Start for Outlier Detection <#quick-start-for-outlier-detection>_How to Contribute <#how-to-contribute>_Inclusion Criteria <#inclusion-criteria>_
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:
.. code-block:: bash
pip install pyod # normal install pip install --upgrade pyod # or update if needed
.. code-block:: bash
conda install -c conda-forge pyod
Alternatively, you can clone and run the setup.py file:
.. code-block:: bash
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 <https://pyod.readthedocs.io/en/latest/pyod.html>_. 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) [#Perini2020Quantifying]_.
- predict_with_rejection(X)\ : Allow the detector to reject (i.e., abstain from making) highly uncertain predictions (output = -2) [#Perini2023Rejection]_.
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 <https://arxiv.org/abs/2206.09426>_ [#Han2022ADBench].
The fully open-sourced ADBench <https://github.com/Minqi824/ADBench> compares 30 anomaly detection algorithms on 57 benchmark datasets.
The organization of ADBench is provided below:
.. image:: https://github.com/Minqi824/ADBench/blob/main/figs/ADBench.png?raw=true :target: https://github.com/Minqi824/ADBench/blob/main/figs/ADBench.png?raw=true :alt: benchmark-fig
For a simpler visualization, we make the comparison of selected models via
compare_all_models.py <https://github.com/yzhao062/pyod/blob/master/examples/compare_all_models.py>_.
.. image:: https://github.com/yzhao062/pyod/blob/development/examples/ALL.png?raw=true :target: https://github.com/yzhao062/pyod/blob/development/examples/ALL.png?raw=true :alt: Comparison_of_All
Additional Topics ^^^^^^^^^^^^^^^^^
Model Save & Load <https://pyod.readthedocs.io/en/latest/model_persistence.html>: Use joblib or pickle for saving and loading PyOD models. Seeexample <https://github.com/yzhao062/pyod/blob/master/examples/save_load_model_example.py>.Fast Train with SUOD <https://pyod.readthedocs.io/en/latest/fast_train.html>: Accelerate training and prediction with the SUOD framework [#Zhao2021SUOD]. Seeexample <https://github.com/yzhao062/pyod/blob/master/examples/suod_example.py>_.Thresholding Outlier Scores <https://pyod.readthedocs.io/en/latest/thresholding.html>: Data-driven approaches for setting contamination levels viaPyThresh <https://github.com/KulikDM/pythresh>.
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 [#Li2021ECOD]_ Probabilistic ABOD Angle-Based Outlier Detection 2008 [#Kriegel2008Angle]_ Probabilistic FastABOD Fast Angle-Based Outlier Detection using approximation 2008 [#Kriegel2008Angle]_ Probabilistic COPOD COPOD: Copula-Based Outlier Detection 2020 [#Li2020COPOD]_ Probabilistic MAD Median Absolute Deviation (MAD) 1993 [#Iglewicz1993How]_ Probabilistic SOS Stochastic Outlier Selection 2012 [#Janssens2012Stochastic]_ Probabilistic QMCD Quasi-Monte Carlo Discrepancy outlier detection 2001 [#Fang2001Wrap]_ Probabilistic KDE Outlier Detection with Kernel Density Functions 2007 [#Latecki2007Outlier]_ Probabilistic Sampling Rapid distance-based outlier detection via sampling 2013 [#Sugiyama2013Rapid]_ Probabilistic GMM Probabilistic Mixture Modeling for Outlier Analysis [#Aggarwal2015Outlier]_ [Ch.2] Linear Model PCA Principal Component Analysis (the sum of weighted projected distances to the eigenvector hyperplanes) 2003 [#Shyu2003A]_ Linear Model KPCA Kernel Principal Component Analysis 2007 [#Hoffmann2007Kernel]_ Linear Model MCD Minimum Covariance Determinant (use the mahalanobis distances as the outlier scores) 1999 [#Hardin2004Outlier]_ [#Rousseeuw1999A]_ Linear Model CD Use Cook's distance for outlier detection 1977 [#Cook1977Detection]_ Linear Model OCSVM One-Class Support Vector Machines 2001 [#Scholkopf2001Estimating]_ Linear Model LMDD Deviation-based Outlier Detection (LMDD) 1996 [#Arning1996A]_ Proximity-Based LOF Local Outlier Factor 2000 [#Breunig2000LOF]_ Proximity-Based COF Connectivity-Based Outlier Factor 2002 [#Tang2002Enhancing]_ Proximity-Based (Incremental) COF Memory Efficient Connectivity-Based Outlier Factor (slower but reduce storage complexity) 2002 [#Tang2002Enhancing]_ Proximity-Based CBLOF Clustering-Based Local Outlier Factor 2003 [#He2003Discovering]_ Proximity-Based LOCI LOCI: Fast outlier detection using the local correlation integral 2003 [#Papadimitriou2003LOCI]_ Proximity-Based HBOS Histogram-based Outlier Score 2012 [#Goldstein2012Histogram]_ Proximity-Based HDBSCAN Density-based clustering based on hierarchical density estimates 2013 [#Campello2013Density]_ Proximity-Based kNN k Nearest Neighbors (use the distance to the kth nearest neighbor as the outlier score) 2000 [#Ramaswamy2000Efficient]_ Proximity-Based AvgKNN Average kNN (use the average distance to k nearest neighbors as the outlier score) 2002 [#Angiulli2002Fast]_ Proximity-Based MedKNN Median kNN (use the median distance to k nearest neighbors as the outlier score) 2002 [#Angiulli2002Fast]_ Proximity-Based SOD Subspace Outlier Detection 2009 [#Kriegel2009Outlier]_ Proximity-Based ROD Rotation-based Outlier Detection 2020 [#Almardeny2020A]_ Outlier Ensembles IForest Isolation Forest 2008 [#Liu2008Isolation]_ Outlier Ensembles INNE Isolation-based Anomaly Detection Using Nearest-Neighbor Ensembles 2018 [#Bandaragoda2018Isolation]_ Outlier Ensembles DIF Deep Isolation Forest for Anomaly Detection 2023 [#Xu2023Deep]_ Outlier Ensembles FB Feature Bagging 2005 [#Lazarevic2005Feature]_ Outlier Ensembles LSCP LSCP: Locally Selective Combination of Parallel Outlier Ensembles 2019 [#Zhao2019LSCP]_ Outlier Ensembles XGBOD Extreme Boosting Based Outlier Detection (Supervised) 2018 [#Zhao2018XGBOD]_ Outlier Ensembles LODA Lightweight On-line Detector of Anomalies 2016 [#Pevny2016Loda]_ Outlier Ensembles SUOD SUOD: Accelerating Large-scale Unsupervised Heterogeneous Outlier Detection (Acceleration) 2021 [#Zhao2021SUOD]_ Neural Networks AutoEncoder Fully connected AutoEncoder (use reconstruction error as the outlier score) [#Aggarwal2015Outlier]_ [Ch.3] Neural Networks VAE Variational AutoEncoder (use reconstruction error as the outlier score) 2013 [#Kingma2013Auto]_ Neural Networks Beta-VAE Variational AutoEncoder (all customized loss term by varying gamma and capacity) 2018 [#Burgess2018Understanding]_ Neural Networks SO_GAAL Single-Objective Generative Adversarial Active Learning 2019 [#Liu2019Generative]_ Neural Networks MO_GAAL Multiple-Objective Generative Adversarial Active Learning 2019 [#Liu2019Generative]_ Neural Networks DeepSVDD Deep One-Class Classification 2018 [#Ruff2018Deep]_ Neural Networks AnoGAN Anomaly Detection with Generative Adversarial Networks 2017 [#Schlegl2017Unsupervised]_ Neural Networks ALAD Adversarially learned anomaly detection 2018 [#Zenati2018Adversarially]_ Neural Networks AE1SVM Autoencoder-based One-class Support Vector Machine 2019 [#Nguyen2019scalable]_ Neural Networks DevNet Deep Anomaly Detection with Deviation Networks 2019 [#Pang2019Deep]_ Graph-based R-Graph Outlier detection by R-graph 2017 [#You2017Provable]_ Graph-based LUNAR LUNAR: Unifying Local Outlier Detection Methods via Graph Neural Networks 2022 [#Goodge2022Lunar]_ Embedding-based EmbeddingOD Multi-modal anomaly detection via foundation model embeddings (text, image) 2025 [#Li2024NLPADBench]_ =================== ================== ====================================================================================================== ===== ========================================
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 <https://pyod.readthedocs.io/en/latest/pyod.html>_ 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 <https://www.analyticsvidhya.com/blog/2019/02/outlier-detection-python-pyod/>_
KDnuggets: Intuitive Visualization of Outlier Detection Methods <https://www.kdnuggets.com/2019/02/outlier-detection-methods-cheat-sheet.html>, An Overview of Outlier Detection Methods from PyOD <https://www.kdnuggets.com/2019/06/overview-outlier-detection-methods-pyod.html>
Towards Data Science: Anomaly Detection for Dummies <https://towardsdatascience.com/anomaly-detection-for-dummies-15f148e559c1>_
"examples/knn_example.py" <https://github.com/yzhao062/pyod/blob/master/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 <https://github.com/yzhao062/pyod/blob/master/examples>_.
#. Initialize a kNN detector, fit the model, and make the prediction.
.. code-block:: python
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).
.. code-block:: python
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.
.. code-block:: python
On Training Data:
KNN ROC:1.0, precision @ rank n:1.0
On Test Data:
KNN ROC:0.9989, precision @ rank n:0.9
.. code-block:: python
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 <https://raw.githubusercontent.com/yzhao062/pyod/master/examples/KNN.png>_\ ):
.. image:: https://raw.githubusercontent.com/yzhao062/pyod/master/examples/KNN.png :target: https://raw.githubusercontent.com/yzhao062/pyod/master/examples/KNN.png :alt: kNN example figure
Reference ^^^^^^^^^
.. [#Aggarwal2015Outlier] Aggarwal, C.C., 2015. Outlier analysis. In Data mining (pp. 237-263). Springer, Cham.
.. [#Aggarwal2015Theoretical] Aggarwal, C.C. and Sathe, S., 2015. Theoretical foundations and algorithms for outlier ensembles.\ ACM SIGKDD Explorations Newsletter\ , 17(1), pp.24-47.
.. [#Aggarwal2017Outlier] Aggarwal, C.C. and Sathe, S., 2017. Outlier ensembles: An introduction. Springer.
.. [#Almardeny2020A] Almardeny, Y., Boujnah, N. and Cleary, F., 2020. A Novel Outlier Detection Method for Multivariate Data. IEEE Transactions on Knowledge and Data Engineering.
.. [#Angiulli2002Fast] 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.
.. [#Arning1996A] 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).
.. [#Bandaragoda2018Isolation] 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.
.. [#Breunig2000LOF] Breunig, M.M., Kriegel, H.P., Ng, R.T. and Sander, J., 2000, May. LOF: identifying density-based local outliers. ACM Sigmod Record\ , 29(2), pp. 93-104.
.. [#Burgess2018Understanding] Burgess, Christopher P., et al. "Understanding disentangling in beta-VAE." arXiv preprint arXiv:1804.03599 (2018).
.. [#Campello2013Density] Campello, R.J.G.B., Moulavi, D. and Sander, J., 2013, April. Density-based clustering based on hierarchical density estimates. In Pacific-Asia Conference on Knowledge Discovery and Data Mining (pp. 160-172). Springer.
.. [#Cook1977Detection] Cook, R.D., 1977. Detection of influential observation in linear regression. Technometrics, 19(1), pp.15-18.
.. [#Chen2024PyOD] Chen, S., Qian, Z., Siu, W., Hu, X., Li, J., Li, S., Qin, Y., Yang, T., Xiao, Z., Ye, W. and Zhang, Y., 2024. PyOD 2: A Python Library for Outlier Detection with LLM-powered Model Selection. arXiv preprint arXiv:2412.12154.
.. [#Fang2001Wrap] 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.
.. [#Goldstein2012Histogram] 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.
.. [#Goodge2022Lunar] 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.
.. [#Gopalan2019PIDForest] Gopalan, P., Sharan, V. and Wieder, U., 2019. PIDForest: Anomaly Detection via Partial Identification. In Advances in Neural Information Processing Systems, pp. 15783-15793.
.. [#Han2022ADBench] Han, S., Hu, X., Huang, H., Jiang, M. and Zhao, Y., 2022. ADBench: Anomaly Detection Benchmark. arXiv preprint arXiv:2206.09426.
.. [#Hardin2004Outlier] 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.
.. [#He2003Discovering] He, Z., Xu, X. and Deng, S., 2003. Discovering cluster-based local outliers. Pattern Recognition Letters\ , 24(9-10), pp.1641-1650.
.. [#Hoffmann2007Kernel] Hoffmann, H., 2007. Kernel PCA for novelty detection. Pattern recognition, 40(3), pp.863-874.
.. [#Iglewicz1993How] Iglewicz, B. and Hoaglin, D.C., 1993. How to detect and handle outliers (Vol. 16). Asq Press.
.. [#Janssens2012Stochastic] 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.
.. [#Kingma2013Auto] Kingma, D.P. and Welling, M., 2013. Auto-encoding variational bayes. arXiv preprint arXiv:1312.6114.
.. [#Kriegel2008Angle] Kriegel, H.P. and Zimek, A., 2008, August. Angle-based outlier detection in high-dimensional data. In KDD '08\ , pp. 444-452. ACM.
.. [#Kriegel2009Outlier] 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.
.. [#Latecki2007Outlier] 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.
.. [#Lazarevic2005Feature] Lazarevic, A. and Kumar, V., 2005, August. Feature bagging for outlier detection. In KDD '05. 2005.
.. [#Li2024NLPADBench] Li, Y., Li, J., Xiao, Z., Yang, T., Nian, Y., Hu, X. and Zhao, Y., 2025. NLP-ADBench: NLP Anomaly Detection Benchmark. In Findings of the Association for Computational Linguistics: EMNLP 2025.
.. [#Li2019MADGAN] 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.
.. [#Li2020COPOD] Li, Z., Zhao, Y., Botta, N., Ionescu, C. and Hu, X. COPOD: Copula-Based Outlier Detection. IEEE International Conference on Data Mining (ICDM), 2020.
.. [#Li2021ECOD] 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.
.. [#Liu2008Isolation] Liu, F.T., Ting, K.M. and Zhou, Z.H., 2008, December. Isolation forest. In International Conference on Data Mining\ , pp. 413-422. IEEE.
.. [#Liu2019Generative] 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.
.. [#Nguyen2019scalable] Nguyen, M.N. and Vien, N.A., 2019. Scalable and interpretable one-class svms with deep learning and random fourier features. In Machine Learning and Knowledge Discovery in Databases: European Conference, ECML PKDD, 2018.
.. [#Pang2019Deep] Pang, Guansong, Chunhua Shen, and Anton Van Den Hengel. "Deep anomaly detection with deviation networks." In KDD, pp. 353-362. 2019.
.. [#Papadimitriou2003LOCI] 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.
.. [#Pevny2016Loda] Pevný, T., 2016. Loda: Lightweight on-line detector of anomalies. Machine Learning, 102(2), pp.275-304.
.. [#Perini2020Quantifying] 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.
.. [#Perini2023Rejection] Perini, L., Davis, J. Unsupervised anomaly detection with rejection. In Proceedings of the Thirty-Seven Conference on Neural Information Processing Systems (NeurIPS), 2023.
.. [#Ramaswamy2000Efficient] 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.
.. [#Rousseeuw1999A] Rousseeuw, P.J. and Driessen, K.V., 1999. A fast algorithm for the minimum covariance determinant estimator. Technometrics\ , 41(3), pp.212-223.
.. [#Ruff2018Deep] 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.
.. [#Schlegl2017Unsupervised] 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.
.. [#Scholkopf2001Estimating] 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.
.. [#Shyu2003A] 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.
.. [#Sugiyama2013Rapid] Sugiyama, M. and Borgwardt, K., 2013. Rapid distance-based outlier detection via sampling. Advances in neural information processing systems, 26.
.. [#Tang2002Enhancing] 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.
.. [#Wang2020adVAE] 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.
.. [#Xu2023Deep] Xu, H., Pang, G., Wang, Y., Wang, Y., 2023. Deep isolation forest for anomaly detection. IEEE Transactions on Knowledge and Data Engineering.
.. [#Yang2024ad] Yang, T., Nian, Y., Li, S., Xu, R., Li, Y., Li, J., Xiao, Z., Hu, X., Rossi, R., Ding, K. and Hu, X., 2024. AD-LLM: Benchmarking Large Language Models for Anomaly Detection. arXiv preprint arXiv:2412.11142.
.. [#You2017Provable] 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.
.. [#Zenati2018Adversarially] 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.
.. [#Zhao2018XGBOD] Zhao, Y. and Hryniewicki, M.K. XGBOD: Improving Supervised Outlier Detection with Unsupervised Representation Learning. IEEE International Joint Conference on Neural Networks\ , 2018.
.. [#Zhao2019LSCP] 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.
.. [#Zhao2021SUOD] 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).
版本历史
v2.1.02026/04/06v2.0.72026/02/27v2.0.62025/12/02v2.0.52025/04/29v2.0.32024/12/22v2.0.22024/09/06v2.0.12024/06/22v1.1.32024/02/09v1.1.22023/11/18v1.1.12023/10/25v1.1.02023/06/25v1.0.82023/03/08v1.0.72022/12/16v1.0.62022/10/24v1.0.52022/09/15v1.0.42022/07/29v1.0.32022/07/05v1.0.22022/06/23v1.0.12022/05/13v1.0.02022/04/23常见问题
相似工具推荐
openclaw
OpenClaw 是一款专为个人打造的本地化 AI 助手,旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚,能够直接接入你日常使用的各类通讯渠道,包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息,OpenClaw 都能即时响应,甚至支持在 macOS、iOS 和 Android 设备上进行语音交互,并提供实时的画布渲染功能供你操控。 这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地,用户无需依赖云端服务即可享受快速、私密的智能辅助,真正实现了“你的数据,你做主”。其独特的技术亮点在于强大的网关架构,将控制平面与核心助手分离,确保跨平台通信的流畅性与扩展性。 OpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者,以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力(支持 macOS、Linux 及 Windows WSL2),即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你
stable-diffusion-webui
stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面,旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点,将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。 无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师,还是想要深入探索模型潜力的开发者与研究人员,都能从中获益。其核心亮点在于极高的功能丰富度:不仅支持文生图、图生图、局部重绘(Inpainting)和外绘(Outpainting)等基础模式,还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外,它内置了 GFPGAN 和 CodeFormer 等人脸修复工具,支持多种神经网络放大算法,并允许用户通过插件系统无限扩展能力。即使是显存有限的设备,stable-diffusion-webui 也提供了相应的优化选项,让高质量的 AI 艺术创作变得触手可及。
everything-claude-code
everything-claude-code 是一套专为 AI 编程助手(如 Claude Code、Codex、Cursor 等)打造的高性能优化系统。它不仅仅是一组配置文件,而是一个经过长期实战打磨的完整框架,旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。 通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能,everything-claude-code 能显著提升 AI 在复杂任务中的表现,帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略,使得模型响应更快、成本更低,同时有效防御潜在的攻击向量。 这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库,还是需要 AI 协助进行安全审计与自动化测试,everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目,它融合了多语言支持与丰富的实战钩子(hooks),让 AI 真正成长为懂上
ComfyUI
ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎,专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式,采用直观的节点式流程图界面,让用户通过连接不同的功能模块即可构建个性化的生成管线。 这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景,也能自由组合模型、调整参数并实时预览效果,轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性,不仅支持 Windows、macOS 和 Linux 全平台,还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构,并率先支持 SDXL、Flux、SD3 等前沿模型。 无论是希望深入探索算法潜力的研究人员和开发者,还是追求极致创作自由度的设计师与资深 AI 绘画爱好者,ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能,使其成为当前最灵活、生态最丰富的开源扩散模型工具之一,帮助用户将创意高效转化为现实。
gemini-cli
gemini-cli 是一款由谷歌推出的开源 AI 命令行工具,它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言,它提供了一条从输入提示词到获取模型响应的最短路径,无需切换窗口即可享受智能辅助。 这款工具主要解决了开发过程中频繁上下文切换的痛点,让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用,还是执行复杂的 Git 操作,gemini-cli 都能通过自然语言指令高效处理。 它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口,具备出色的逻辑推理能力;内置 Google 搜索、文件操作及 Shell 命令执行等实用工具;更独特的是,它支持 MCP(模型上下文协议),允许用户灵活扩展自定义集成,连接如图像生成等外部能力。此外,个人谷歌账号即可享受免费的额度支持,且项目基于 Apache 2.0 协议完全开源,是提升终端工作效率的理想助手。
markitdown
MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具,专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片(含 OCR)、音频(含语音转录)、HTML 乃至 YouTube 链接等多种格式的解析,能够精准提取文档中的标题、列表、表格和链接等关键结构信息。 在人工智能应用日益普及的今天,大语言模型(LLM)虽擅长处理文本,却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点,它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式,成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外,它还提供了 MCP(模型上下文协议)服务器,可无缝集成到 Claude Desktop 等 LLM 应用中。 这款工具特别适合开发者、数据科学家及 AI 研究人员使用,尤其是那些需要构建文档检索增强生成(RAG)系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性,但其核心优势在于为机器