项目地址https://github.com/yzhao062/Pyod#ramaswamy2000efficient
参考资料
知乎-用PyOD工具库进行「异常检测」
使用PyOD库在Python中进行离群值检测
PyOD在线文档
CSDN-离群点异常检测及可视化分析工具pyod测试

一、PyOD介绍

异常检测(又称outlier detection、anomaly detection,离群值检测)是一种重要的数据挖掘方法可以找到与“主要数据分布”不同的异常值(deviant from the general data distribution),比如从信用卡交易中找出诈骗案例,从正常的网络数据流中找出入侵,有非常广泛的商业应用价值。同时它可以被用于机器学习任务中的预处理(preprocessing),防止因为少量异常点存在而导致的训练或预测失败。

二、PyOD主要亮点

  • 包括近20种常见的异常检测算法,比如经典的LOF/LOCI/ABOD以及最新的深度学习如对抗生成模型(GAN)和集成异常检测(outlier ensemble)
  • 支持不同版本的Python:包括2.7和3.5+;支持多种操作系统:windows,macOS和Linux
  • 简单易用且一致的API只需要几行代码就可以完成异常检测,方便评估大量算法
  • 使用JIT和并行化(parallelization)进行优化,加速算法运行及扩展性(scalability),可以处理大量数据

三、工具库相关重要信息汇总:

四、作者介绍:

image.png
微调
数据挖掘 | 机器学习系统 | 前咨询师 | 在读博士
职业经历:
异常点检测PyOD - 图2斯坦福大学 (Stanford University) · Visiting Student Researcher
异常点检测PyOD - 图3艾昆纬 (IQVIA) · machine learning research intern
异常点检测PyOD - 图4普华永道 · 高级数据科学家
教育经历:
异常点检测PyOD - 图5卡内基梅隆大学 (Carnegie Mellon University) · 信息系统
异常点检测PyOD - 图6多伦多大学 (University of Toronto) · 计算机科学
异常点检测PyOD - 图7辛辛那提大学 · 计算机工程(CE)
异常点检测PyOD - 图8山西省实验中学
个人简介
1. 机器学习系统架构师,参与设计了10个工具库/系统,GitHub Star>10000,下载量>300,0000
2. 生物制药 x 机器学习: https://github.com/mims-harvard/TDC
3. 大规模异常检测模型 SUOD:https://github.com/yzhao062/suod
4. PyOD异常检测工具库:https://github.com/yzhao062/pyod
5. 个人主页:https://www.andrew.cmu.edu/user/yuezhao2
6. GayHub: https://github.com/yzhao062
7. Google Scholar: https://scholar.google.com/cita

五、API介绍与实例(API References & Examples)

Examples可下载github项目中查看和运行。
image.png

特别需要注意的是,异常检测算法基本都是无监督学习,所以只需要X(输入数据),而不需要y(标签)。PyOD的使用方法和Sklearn中聚类分析很像,它的检测器(detector)均有统一的API。所有的PyOD检测器clf均有统一的API以便使用,完整的API使用参考可以查阅(API CheatSheet - pyod 0.6.8 documentation):

  • fit(X): 用数据X来“训练/拟合”检测器clf。即在初始化检测器clf后,用X来“训练”它。
  • fit_predict_score(X, y): 用数据X来训练检测器clf,并预测X的预测值,并在真实标签y上进行评估。此处的y只是用于评估,而非训练
  • decision_function(X): 在检测器clf被fit后,可以通过该函数来预测未知数据的异常程度,返回值为原始分数,并非0和1。返回分数越高,则该数据点的异常程度越高
  • predict(X): 在检测器clf被fit后,可以通过该函数来预测未知数据的异常标签,返回值为二分类标签(0为正常点,1为异常点)
  • predict_proba(X): 在检测器clf被fit后,预测未知数据的异常概率,返回该点是异常点概率

当检测器clf被初始化且fit(X)函数被执行后,clf就会生成两个重要的属性:

  • decision_scores: 数据X上的异常打分,分数越高,则该数据点的异常程度越高
  • labels_: 数据X上的异常标签,返回值为二分类标签(0为正常点,1为异常点)

不难看出,当我们初始化一个检测器clf后,可以直接用数据X来“训练”clf,之后我们便可以得到X的异常分值(clf.decisionscores)以及异常标签(clf.labels)。当clf被训练后(当fit函数被执行后),我们可以使用decision_function()和predict()函数来对未知数据进行训练。
在有了背景知识后,我们可以使用PyOD来实现一个简单的异常检测实例:

  1. from pyod.models.knn import KNN # imprt kNN分类器
  2. # 训练一个kNN检测器
  3. clf_name = 'kNN'
  4. clf = KNN() # 初始化检测器clf
  5. clf.fit(X_train) # 使用X_train训练检测器clf
  6. # 返回训练数据X_train上的异常标签和异常分值
  7. y_train_pred = clf.labels_ # 返回训练数据上的分类标签 (0: 正常值, 1: 异常值)
  8. y_train_scores = clf.decision_scores_ # 返回训练数据上的异常值 (分值越大越异常)
  9. # 用训练好的clf来预测未知数据中的异常值
  10. y_test_pred = clf.predict(X_test) # 返回未知数据上的分类标签 (0: 正常值, 1: 异常值)
  11. y_test_scores = clf.decision_function(X_test) # 返回未知数据上的异常值 (分值越大越异常)

不难看出,PyOD的API和scikit-learn非常相似,只需要几行就可以得到数据的异常值。当检测器得到输出后,我们可以用以下代码评估其表现,或者直接可视化分类结果(图2

  1. # 评估预测结果
  2. print("\nOn Test Data:")
  3. evaluate_print(clf_name, y_test, y_test_scores)
  4. # 可视化
  5. visualize(clf_name, X_train, y_train, X_test, y_test, y_train_pred,
  6. y_test_pred, show_figure=True, save_figure=False)

异常点检测PyOD - 图10图2. 预测结果(右图)与真实结果(左图)对比

六、代码:

  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @File : outlierDetection.py
  5. @Modify Time @Author @Version @Description
  6. ------------ ------- -------- -----------
  7. 2021/8/12 14:06 SeafyLiang 1.0 离群点检测pyod
  8. """
  9. import numpy as np
  10. from scipy import stats
  11. import matplotlib.pyplot as plt
  12. import matplotlib.font_manager
  13. # 检测数据集中异常值的模型
  14. from pyod.models.abod import ABOD
  15. from pyod.models.cblof import CBLOF
  16. # from pyod.models.feature_bagging import FeatureBagging
  17. from pyod.models.hbos import HBOS
  18. from pyod.models.iforest import IForest
  19. from pyod.models.knn import KNN
  20. # from pyod.models.loci import LOCI
  21. # from pyod.models.sod import SOD
  22. from pyod.models.lof import LOF
  23. from pyod.models.mcd import MCD
  24. from pyod.models.ocsvm import OCSVM
  25. from pyod.models.pca import PCA
  26. from pyod.utils.data import generate_data, get_outliers_inliers
  27. """
  28. 参考资料:
  29. https://blog.csdn.net/weixin_41697507/article/details/89408236
  30. https://blog.csdn.net/sparkexpert/article/details/81195418
  31. https://github.com/yzhao062/Pyod#ramaswamy2000efficient
  32. """
  33. # 创建一个带有异常值的随机数据集并绘制它
  34. # generate random data with two features
  35. X_train, Y_train = generate_data(n_train=200, train_only=True, n_features=2)
  36. # by default the outlier fraction is 0.1 in generate data function
  37. outlier_fraction = 0.1
  38. # store outliers and inliers in different numpy arrays
  39. x_outliers, x_inliers = get_outliers_inliers(X_train, Y_train)
  40. n_inliers = len(x_inliers)
  41. n_outliers = len(x_outliers)
  42. # separate the two features and use it to plot the data
  43. F1 = X_train[:, [0]].reshape(-1, 1)
  44. F2 = X_train[:, [1]].reshape(-1, 1)
  45. # create a meshgrid
  46. xx, yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
  47. # scatter plot
  48. plt.scatter(F1, F2)
  49. plt.xlabel('F1')
  50. plt.ylabel('F2')
  51. plt.show()
  52. """
  53. Model 1 Angle-based Outlier Detector (ABOD)
  54. Model 2 Cluster-based Local Outlier Factor (CBLOF)
  55. Model 3 Feature Bagging
  56. Model 4 Histogram-base Outlier Detection (HBOS)
  57. Model 5 Isolation Forest
  58. Model 6 K Nearest Neighbors (KNN)
  59. Model 7 Fast outlier detection using the local correlation integral(LOCI)
  60. Model 8 Subspace Outlier Detection (SOD)
  61. Model 9 Local Outlier Factor (LOF)
  62. Model 10 Minimum Covariance Determinant (MCD)
  63. Model 11 One-class SVM (OCSVM)
  64. Model 12 Principal Component Analysis (PCA)
  65. """
  66. # 创建一个dictionary并添加要用于检测异常值的所有模型
  67. classifiers = {
  68. 'ABOD': ABOD(contamination=outlier_fraction),
  69. 'CBLOF': CBLOF(contamination=outlier_fraction),
  70. # 'Feature Bagging': FeatureBagging(contamination=outlier_fraction),
  71. 'HBOS': HBOS(contamination=outlier_fraction),
  72. 'IForest': IForest(contamination=outlier_fraction),
  73. 'KNN': KNN(contamination=outlier_fraction),
  74. # 'LOCI': LOCI(contamination=outlier_fraction, ),
  75. # 'SOD': SOD(contamination=outlier_fraction, ),
  76. 'LOF': LOF(contamination=outlier_fraction, ),
  77. 'MCD': MCD(contamination=outlier_fraction, ),
  78. 'OCSVM': OCSVM(contamination=outlier_fraction, ),
  79. 'PCA': PCA(contamination=outlier_fraction, ),
  80. }
  81. # 将数据拟合到我们在dictionary中添加的每个模型,然后,查看每个模型如何检测异常值
  82. # set the figure size
  83. plt.figure(figsize=(10, 10))
  84. for i, (clf_name, clf) in enumerate(classifiers.items()):
  85. print()
  86. print(i + 1, 'fitting', clf_name)
  87. # fit the data and tag outliers
  88. clf.fit(X_train)
  89. scores_pred = clf.decision_function(X_train) * -1
  90. y_pred = clf.predict(X_train)
  91. threshold = stats.scoreatpercentile(scores_pred,
  92. 100 * outlier_fraction)
  93. n_errors = (y_pred != Y_train).sum()
  94. # plot the levels lines and the points
  95. Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) * -1
  96. Z = Z.reshape(xx.shape)
  97. subplot = plt.subplot(3, 4, i + 1)
  98. subplot.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7),
  99. cmap=plt.cm.Blues_r)
  100. a = subplot.contour(xx, yy, Z, levels=[threshold],
  101. linewidths=2, colors='red')
  102. subplot.contourf(xx, yy, Z, levels=[threshold, Z.max()],
  103. colors='orange')
  104. b = subplot.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c='white',
  105. s=20, edgecolor='k')
  106. c = subplot.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c='black',
  107. s=20, edgecolor='k')
  108. subplot.axis('tight')
  109. subplot.legend(
  110. [a.collections[0], b, c],
  111. ['learned decision function', 'true inliers', 'true outliers'],
  112. prop=matplotlib.font_manager.FontProperties(size=10),
  113. loc='lower right')
  114. subplot.set_xlabel("%d. %s (errors: %d)" % (i + 1, clf_name, n_errors))
  115. subplot.set_xlim((-7, 7))
  116. subplot.set_ylim((-7, 7))
  117. plt.show()

6.1 效果图

image.pngimage.png