sklearn異常檢測demo


sklearn 異常檢測demo代碼走讀

# 0基礎學python,讀代碼學習python組件api
import time
 
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
 
from sklearn import svm
from sklearn.datasets import make_moons, make_blobs
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
 
print(__doc__)
 
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
 
# Example settings
n_samples = 300
outliers_fraction = 0.15
n_outliers = int(outliers_fraction * n_samples)
n_inliers = n_samples - n_outliers
 
# define outlier/anomaly detection methods to be compared
# 四種異常檢測算法,之后的文章詳細介紹
anomaly_algorithms = [
    ("Robust covariance", EllipticEnvelope(contamination=outliers_fraction)),
    ("One-Class SVM", svm.OneClassSVM(nu=outliers_fraction, kernel="rbf",
                                      gamma=0.1)),
    ("Isolation Forest", IsolationForest(contamination=outliers_fraction,
                                         random_state=42)),
    ("Local Outlier Factor", LocalOutlierFactor(
        n_neighbors=35, contamination=outliers_fraction))]
 
# Define datasets
blobs_params = dict(random_state=0, n_samples=n_inliers, n_features=2)
datasets = [
    # make_blobes用於生成聚類數據。centers表示聚類中心,cluster_std表示聚類數據方差。返回值(數據, 類別)
    # **用於傳遞dict key-value參數,*用於傳遞元組不定數量參數。
    make_blobs(centers=[[0, 0], [0, 0]], cluster_std=0.5,
               **blobs_params)[0],
    make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[0.5, 0.5],
               **blobs_params)[0],
    make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[1.5, .3],
               **blobs_params)[0],
     
    # make_moons用於生成月亮形數據。返回值數據(x, y)
    4. * (make_moons(n_samples=n_samples, noise=.05, random_state=0)[0] -
          np.array([0.5, 0.25])),
    14. * (np.random.RandomState(42).rand(n_samples, 2) - 0.5)]
 
# Compare given classifiers under given settings
# np.meshgrid生產成網格數據
# 如輸入x = [0, 1, 2, 3] y = [0, 1, 2],則輸出
# xx 0 1 2 3   yy 0 0 0 0
#    0 1 2 3      1 1 1 1
#    0 1 2 3      2 2 2 2
xx, yy = np.meshgrid(np.linspace(-7, 7, 150),
                     np.linspace(-7, 7, 150))
 
# figure生成畫布,subplots_adjust子圖的間距調整,左邊距,右邊距,下邊距,上邊距,列間距,行間距
plt.figure(figsize=(len(anomaly_algorithms) * 2 + 3, 12.5))
plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05,
                    hspace=.01)
 
plot_num = 1
rng = np.random.RandomState(42)
 
for i_dataset, X in enumerate(datasets):
    # Add outliers
    # np.concatenate數組拼接。axis=0行增加,axis=1列增加(對應行拼接)。
    X = np.concatenate([X, rng.uniform(low=-6, high=6,
                       size=(n_outliers, 2))], axis=0)
 
    for name, algorithm in anomaly_algorithms:
        t0 = time.time()
        # 專門用於評估執行時間,無用代碼
        algorithm.fit(X)
        t1 = time.time()
        # 定位子圖位置。參數:列,行,序號
        plt.subplot(len(datasets), len(anomaly_algorithms), plot_num)
        if i_dataset == 0:
            plt.title(name, size=18)
 
        # fit the data and tag outliers
        # 訓練與預測
        if name == "Local Outlier Factor":
            y_pred = algorithm.fit_predict(X)
        else:
            y_pred = algorithm.fit(X).predict(X)
 
        # plot the levels lines and the points
        # 用訓練的模型預測網格數據點,主要是要得到聚類模型邊緣
        if name != "Local Outlier Factor":  # LOF does not implement predict
            # ravel()多維數組平鋪為一維數組。np.c_ cloumn列連接,np.r_ row行連接。
            Z = algorithm.predict(np.c_[xx.ravel(), yy.ravel()])
            # reshape這里把一維數組轉化為二維數組
            Z = Z.reshape(xx.shape)
            # plt.contour畫等高線。Z表示對應點類別,可以理解為不同的高度,plt.contour就是要畫出不同高度間的分界線。
            plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='black')
 
        colors = np.array(['#377eb8', '#ff7f00'])
        plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[(y_pred + 1) // 2])
 
        # x軸范圍
        plt.xlim(-7, 7)
        plt.ylim(-7, 7)
        # x軸坐標
        plt.xticks(())
        plt.yticks(())
        # 坐標圖上顯示的文字
        plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),
                 transform=plt.gca().transAxes, size=15,
                 horizontalalignment='right')
        plot_num += 1
 
plt.show()

執行結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM