自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 離群點(diǎn)檢測算法-OCSVM

開發(fā) 前端
OCSVM根據(jù)正常類的屬性建立模型,以檢測非正常類數(shù)據(jù)。它在高維空間中將數(shù)據(jù)點(diǎn)與原點(diǎn)分離,并最大化該超平面到原點(diǎn)的距離。換句話說,原點(diǎn)就是算法試圖從正常類中分離出來的類。

分類問題通常采用監(jiān)督學(xué)習(xí)算法解決,如隨機(jī)森林、支持向量機(jī)、邏輯回歸器等。監(jiān)督學(xué)習(xí)算法需要已知目標(biāo)來建立模型,但通常只能觀察到正常的數(shù)據(jù)模式,而看不到罕見事件。由于罕見事件的目標(biāo)數(shù)據(jù)要么不可用,要么數(shù)量不足以進(jìn)行模型訓(xùn)練,單類支持向量機(jī)(OCSVM)可以解決只有一類數(shù)據(jù)的問題,對正常類的屬性進(jìn)行建模,能夠檢測到異常數(shù)據(jù)。本章將解釋支持向量機(jī) (SVM) 的概念,并介紹如何將其發(fā)展為單類 SVM (OCSVM),以及它是如何定義離群值的。

支持向量機(jī)(SVM)

支持向量機(jī)(SVM)是一種監(jiān)督學(xué)習(xí)算法,可處理分類和回歸問題,由Vladimir Vapnik及其同事在1992-1995年在AT&T貝爾實(shí)驗(yàn)室開發(fā)?,F(xiàn)已廣泛應(yīng)用于分類問題。

SVM 有一個(gè)非常巧妙的特性。它可以創(chuàng)建一個(gè)非線性決策邊界來分離兩個(gè)類別。它在高維空間中找到分離的方法非常優(yōu)雅。首先將無法用直線分離的數(shù)據(jù)點(diǎn)投影到高維空間,然后就會出現(xiàn)一個(gè) "直線 "超平面,將一個(gè)類別的數(shù)據(jù)點(diǎn)與另一個(gè)類別的數(shù)據(jù)點(diǎn)分離開來。當(dāng)超平面投影回原始空間時(shí),它將是一條非線性曲線。這可以從圖 (B) 中看出。左圖顯示,藍(lán)點(diǎn)和紅點(diǎn)無法用任何直線分開。但如果將所有點(diǎn)投影到三維空間,結(jié)果就變成了線性分離。當(dāng)數(shù)據(jù)投影回原始空間時(shí),邊界則是一條非線性曲線。為什么在高維空間中成分分離會變得更容易?這要追溯到瓦普尼克-切沃能基斯(VC)理論。該理論認(rèn)為,映射到更高維度的空間往往能提供更強(qiáng)的分類能力。

SVMSVM

SVM在高維空間中尋找支持向量,如上圖所示的虛線超平面。支持向量位于特征空間中每個(gè)類別的邊緣,通過最大化超平面的間隔來實(shí)現(xiàn)兩個(gè)類別的最大分離度。除了支持向量之間的區(qū)域外,SVM還允許一些點(diǎn)以避免過度擬合。

從 SVM 到單類 SVM

建立算法來區(qū)分一個(gè)類和另一個(gè)類的方法之一是使用單類 SVM。這種方法將所有數(shù)據(jù)點(diǎn)從高維空間的原點(diǎn)分離出來,并將該超平面到原點(diǎn)的距離最大化,以此來從正常類中分離出目標(biāo)類。另一種方法是使用球面進(jìn)行分離,而不是超平面。

OVSVMOVSVM

OCSVM 如何定義離群點(diǎn)得分?

OCSVM 離群點(diǎn)得分是數(shù)據(jù)點(diǎn)到超平面的距離,也稱為相似度。相似度的計(jì)算方法是使用核函數(shù)如徑向基函數(shù)、線性函數(shù)、多項(xiàng)式函數(shù)或西格瑪函數(shù)計(jì)算相應(yīng)的 N 維相似度矩陣之和。徑向基函數(shù)簡單地計(jì)算輸入 x 與固定點(diǎn) c 之間的距離。如。

OCSVM 對 RBF 和參數(shù)的選擇很敏感

OCSVM 對于內(nèi)核選擇和部分超參數(shù)非常敏感,這會導(dǎo)致不同選擇下性能有很大差異。根據(jù)文獻(xiàn)的記錄,一個(gè)名為nu的重要超參數(shù)決定了數(shù)據(jù)點(diǎn)成為訓(xùn)練數(shù)據(jù)中離群點(diǎn)的概率。它的取值介于0和1之間。當(dāng)nu為10%時(shí),意味著10%的數(shù)據(jù)被支持邊界錯誤地分類為離群值,也意味著10%的數(shù)據(jù)位于邊界上。具體來說,nu需要在離群值和支持向量數(shù)量之間進(jìn)行權(quán)衡。

由于OCSVM對超參數(shù)非常敏感,解決方法是建立多個(gè)模型,然后平均預(yù)測結(jié)果以獲得更穩(wěn)定的結(jié)果。在接下來的章節(jié)中,將用一系列nu值建立模型,然后對預(yù)測結(jié)果進(jìn)行匯總。

建模流程

步驟 1 - 建立模型

我們將使用數(shù)據(jù)生成過程 (DGP) 模擬 500 個(gè)觀測值和六個(gè)變量,其中異常值比例設(shè)定為 5%。目標(biāo)變量為 Y,我們將只使用 X 數(shù)據(jù)來建立無監(jiān)督模型 OCSVM。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyod.utils.data import generate_data
contamination = 0.05 # percentage of outliers
n_train = 500       # number of training points
n_test = 500        # number of testing points
n_features = 6      # number of features
X_train, X_test, y_train, y_test = generate_data(
    n_train=n_train, 
    n_test=n_test, 
    n_features= n_features, 
    cnotallow=contamination, 
    random_state=123)

X_train_pd = pd.DataFrame(X_train)
X_train_pd.head()

圖片圖片

下圖是前兩個(gè)變量的散點(diǎn)圖。黃色圓點(diǎn)為異常值,紫色圓點(diǎn)為正常數(shù)據(jù)點(diǎn)。

# Plot
plt.scatter(X_train_pd[0], X_train_pd[1], c=y_train, alpha=0.8)
plt.title('Scatter plot')
plt.xlabel('x0')
plt.ylabel('x1')
plt.show()

圖片

下面的代碼通過指定并擬合了模型 ocsvm,其中參數(shù) cnotallow=0.05 表示離群值的百分比為 5%。這一參數(shù)對離群值分?jǐn)?shù)的計(jì)算并沒有影響。如果沒有指定,PyOD 的默認(rèn)值為 10%。接下來,函數(shù) decision_function() 用于計(jì)算觀測值的離群值,而函數(shù) predict() 則根據(jù)contamination的賦值來決定輸出 "1" 或 "0"。最后,語法 .threshold_ 可以顯示指定contamination下的閾值。

from pyod.models.ocsvm import OCSVM
ocsvm = OCSVM(cnotallow=0.05)  
ocsvm.fit(X_train)

# Training data
y_train_scores = ocsvm.decision_function(X_train)
y_train_pred = ocsvm.predict(X_train)

# Test data
y_test_scores = ocsvm.decision_function(X_test)
y_test_pred = ocsvm.predict(X_test) # outlier labels (0 or 1)

def count_stat(vector):
    # Because it is '0' and '1', we can run a count statistic. 
    unique, counts = np.unique(vector, return_counts=True)
    return dict(zip(unique, counts))

print("The training data:", count_stat(y_train_pred))
print("The training data:", count_stat(y_test_pred))
# Threshold for the defined comtanimation rate
print("The threshold for the defined comtanimation rate:" , ocsvm.threshold_)
The training data: {0: 475, 1: 25}
The training data: {0: 475, 1: 25}
The threshold for the defined comtanimation rate: 
29.680071121036956

我們可以通過.get_params() 打印出超參數(shù)值:

ocsvm.get_params()
{'cache_size': 200,
 'coef0': 0.0,
 'contamination': 0.05,
 'degree': 3,
 'gamma': 'auto',
 'kernel': 'rbf',
 'max_iter': -1,
 'nu': 0.5,
 'shrinking': True,
 'tol': 0.001,
 'verbose': False}

OCSVM的主要參數(shù)與核函數(shù)密切相關(guān),默認(rèn)情況下使用rbf核函數(shù),nu值為0.5。此外,核函數(shù)中的獨(dú)立項(xiàng)coef0在poly和sigmoid中具有意義。對于多項(xiàng)式核函數(shù)(poly),degree決定了多項(xiàng)式函數(shù)的階數(shù)。模型優(yōu)化的最大迭代次數(shù)由max_iterint設(shè)置,默認(rèn)為-1,表示在優(yōu)化達(dá)到收斂之前沒有限制。停止條件的容差可通過參數(shù)tol進(jìn)行設(shè)置。catch_size決定了RAM的大小,從而影響了計(jì)算機(jī)RAM的使用率,默認(rèn)值為200(MB)。在內(nèi)存足夠的情況下,可以選擇將其調(diào)整為更高的值,例如500(MB)或1000(MB)。通常情況下,無需過于擔(dān)心此參數(shù)。

步驟 2 - 確定合理的閾值

離群值得分衡量離群值和正常數(shù)據(jù)點(diǎn)的偏差,所以可以使用離群值得分的直方圖來了解分布情況。直方圖展示了離群值高的數(shù)據(jù)點(diǎn)所占的百分比,從而有助于確定合理的閾值。圖 (E.2) 建議將閾值設(shè)為 16.0,因?yàn)橹狈綀D中存在一個(gè)自然切點(diǎn),閾值決定了異常組的大小。

import matplotlib.pyplot as plt
plt.hist(y_train_scores, bins='auto')  # arguments are passed to np.histogram
plt.title("Histogram with 'auto' bins")
plt.xlabel('One-class SVM outlier score')
plt.show()

圖片圖片

第 3 步 - 顯示正常組和異常組的描述性統(tǒng)計(jì)結(jié)果

離群值得分衡量離群值和正常數(shù)據(jù)點(diǎn)的偏差,所以可以使用離群值得分的直方圖來了解分布情況。直方圖展示了離群值高的數(shù)據(jù)點(diǎn)所占的百分比,從而有助于確定合理的閾值。上圖建議將閾值設(shè)為 16.0,因?yàn)橹狈綀D中存在一個(gè)自然切點(diǎn),閾值決定了異常組的大小。

threshold = ocsvm.threshold_ # Or other value from the above histogram

def descriptive_stat_threshold(df,pred_score, threshold):
    # Let's see how many '0's and '1's.
    df = pd.DataFrame(df)
    df['Anomaly_Score'] = pred_score
    df['Group'] = np.where(df['Anomaly_Score']< threshold, 'Normal', 'Outlier')

    # Now let's show the summary statistics:
    cnt = df.groupby('Group')['Anomaly_Score'].count().reset_index().rename(columns={'Anomaly_Score':'Count'})
    cnt['Count %'] = (cnt['Count'] / cnt['Count'].sum()) * 100 # The count and count %
    stat = df.groupby('Group').mean().round(2).reset_index() # The avg.
    stat = cnt.merge(stat, left_notallow='Group',right_notallow='Group') # Put the count and the avg. together
    return (stat)

descriptive_stat_threshold(X_train,y_train_scores, threshold)

圖片圖片

模型評估中的關(guān)鍵指標(biāo)包括計(jì)數(shù)百分比和特征均值。閾值的選擇將決定離群值的數(shù)量,較高的閾值將導(dǎo)致離群值減少。特征均值要與領(lǐng)域知識保持一致,如有偏離應(yīng)重新檢查或刪除該特征。在進(jìn)行特征標(biāo)注時(shí)需要有效展示。離群組的平均異常得分應(yīng)高于正常組。我們可以利用混淆矩陣來評估模型性能,該模型成功識別了全部25個(gè)離群值。

Actual_pred = pd.DataFrame({'Actual': y_test, 'Anomaly_Score': y_test_scores})
Actual_pred['Pred'] = np.where(Actual_pred['Anomaly_Score']< threshold,0,1)
pd.crosstab(Actual_pred['Actual'],Actual_pred['Pred'])

圖片圖片

通過聚合多個(gè)模型實(shí)現(xiàn)模型穩(wěn)定性

OCSVM是一種基于鄰近度的算法,對異常值敏感且容易過擬合,特別是在第(D)節(jié)中。為了建立穩(wěn)定的模型結(jié)果,應(yīng)建立多個(gè)參數(shù)范圍各異的模型,然后匯總預(yù)測結(jié)果。

PyOD模塊提供了四種匯總結(jié)果的方法:平均值(Average)、最大值的最大值(MOM)、最大值的平均值(AOM)、平均值的最大值(MOA)。安裝這些函數(shù)使用 pip install combo。請注意,只需使用一種聚合方法。另外,輸入數(shù)據(jù)已經(jīng)被標(biāo)準(zhǔn)化處理,但許多函數(shù)會自動進(jìn)行標(biāo)準(zhǔn)化處理。

由于nu參數(shù)最敏感,因此需要建立多個(gè) nu 值范圍廣泛的模型,總共會有 11 個(gè)模型。我們準(zhǔn)備 11 列的空數(shù)據(jù)幀來存儲這些模型的預(yù)測結(jié)果。

from pyod.models.combination import aom, moa, average, maximization
from pyod.utils.utility import standardizer
from pyod.models.ocsvm import OCSVM

# Standardize data
X_train_norm, X_test_norm = standardizer(X_train, X_test)

# Test a range of nu
k_list = [0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99]
n_clf = len(k_list)
# Just prepare data frames so we can store the model results
train_scores = np.zeros([X_train.shape[0], n_clf])
test_scores = np.zeros([X_test.shape[0], n_clf])

# Modeling
for i in range(n_clf):
    k = k_list[i]
    ocsvm = OCSVM(nu=k,cnotallow=0.05)  
    ocsvm.fit(X_train_norm)
    # Store the results in each column:
    train_scores[:, i] = ocsvm.decision_function(X_train_norm) 
    test_scores[:, i] = ocsvm.decision_function(X_test_norm) 
# Decision scores have to be normalized before combination
train_scores_norm, test_scores_norm = standardizer(train_scores,test_scores)

預(yù)測模型的十個(gè)分?jǐn)?shù)存儲在 "train_scores" 中,并對其進(jìn)行了歸一化處理,以便對十個(gè)預(yù)測結(jié)果進(jìn)行平均。PyOD 模塊提供了四種聚合方法,你只需選擇其中一種即可得出匯總結(jié)果。

# Combination by average
# The test_scores_norm is 500 x 10. The "average" function will take the average of the 10 columns. The result "y_by_average" is a single column: 
y_train_by_average = average(train_scores_norm)
y_test_by_average = average(test_scores_norm)
import matplotlib.pyplot as plt
plt.hist(y_train_by_average, bins='auto') # arguments are passed to np.histogram
plt.title("Combination by average")
plt.show()

訓(xùn)練數(shù)據(jù)平均預(yù)測值直方圖訓(xùn)練數(shù)據(jù)平均預(yù)測值直方圖

圖表顯示閾值為1.40,根據(jù)總分可得到描述性統(tǒng)計(jì),發(fā)現(xiàn)有25個(gè)數(shù)據(jù)點(diǎn)為異常值。讀者可以對表(D.3)進(jìn)行類似的解釋。

descriptive_stat_threshold(
      X_train,y_train_by_average, 1.4)

圖片圖片

OCSVMA 算法總結(jié)

OCSVM根據(jù)正常類的屬性建立模型,以檢測非正常類數(shù)據(jù)。它在高維空間中將數(shù)據(jù)點(diǎn)與原點(diǎn)分離,并最大化該超平面到原點(diǎn)的距離。換句話說,原點(diǎn)就是算法試圖從正常類中分離出來的類。

責(zé)任編輯:武曉燕 來源: 數(shù)據(jù)STUDIO
相關(guān)推薦

2024-05-30 12:50:54

2023-03-13 13:35:00

幾何算法矩形碰撞檢測

2017-09-20 16:25:00

深度學(xué)習(xí)視覺領(lǐng)域計(jì)算機(jī)

2020-11-02 13:44:35

算法數(shù)據(jù)科學(xué)Python

2018-01-23 16:16:03

開源技術(shù) Facebook

2018-09-17 15:30:05

機(jī)器學(xué)習(xí)密度異常值

2020-11-02 11:24:52

算法人臉識別技術(shù)

2020-10-18 07:15:53

Python異常檢測算法開發(fā)

2009-07-15 10:40:06

碰撞檢測算法Java ME

2024-04-26 10:00:03

自動駕駛模型

2023-11-13 22:17:54

YOLO-NAS目標(biāo)檢測

2020-12-24 19:01:14

iForest大數(shù)據(jù)檢測算法

2024-07-18 00:00:25

PyTorch神經(jīng)網(wǎng)絡(luò)

2024-06-05 09:26:50

2021-07-24 11:23:41

算法開源技術(shù)

2022-03-07 10:04:09

機(jī)器學(xué)習(xí)訓(xùn)練模型

2020-11-10 15:22:46

算法PythonIoU

2024-09-09 14:57:31

2022-02-14 11:37:59

自動駕駛算法技術(shù)

2020-05-20 07:00:00

DevOps端點(diǎn)檢測網(wǎng)絡(luò)攻擊
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號