#LOF算法


a.每個數據點,計算它與其他點的距離
b.找到它的K近鄰,計算LOF得分

clf=LocalOutlierFactor(n_neighbors=20,algorithm='auto',contamination=0.1,n_jobs=-1,p=2)

參數含義

●n_neighbors=20:即LOF算法中的k的值,檢測的鄰域點個數超過樣本數則使用所有的樣本進行檢測
●algorithm = 'auto':使用的求解算法,使用默認值即可
●contamination = 0.1:范圍為 (0, 0.5),表示樣本中的異常點比例,默認為 0.1
● n_jobs = -1:並行任務數,設置為-1表示使用所有CPU進行工作
● p = 2:距離度量函數,默認使用歐式距離。

def localoutlierfactor(data, predict, k):
    from sklearn.neighbors import LocalOutlierFactor
    clf = LocalOutlierFactor(n_neighbors=k + 1, algorithm='auto', contamination=0.1, n_jobs=-1)
    clf.fit(data)
    # 記錄 k 鄰域距離
    predict['k distances'] = clf.kneighbors(predict)[0].max(axis=1)
    # 記錄 LOF 離群因子,做相反數處理
    predict['local outlier factor'] = -clf._decision_function(predict.iloc[:, :-1])
    return predict

def plot_lof(result, method):
    import matplotlib.pyplot as plt
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用來正常顯示中文標簽
    plt.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負號
    plt.figure(figsize=(8, 4)).add_subplot(111)
    plt.scatter(result[result['local outlier factor'] > method].index,
                result[result['local outlier factor'] > method]['local outlier factor'], c='red', s=50,
                marker='.', alpha=None,
                label='離群點')
    plt.scatter(result[result['local outlier factor'] <= method].index,
                result[result['local outlier factor'] <= method]['local outlier factor'], c='black', s=50,
                marker='.', alpha=None, label='正常點')
    plt.hlines(method, -2, 2 + max(result.index), linestyles='--')
    plt.xlim(-2, 2 + max(result.index))
    plt.title('LOF局部離群點檢測', fontsize=13)
    plt.ylabel('局部離群因子', fontsize=15)
    plt.legend()
    plt.show()

def lof(data, predict=None, k=5, method=1, plot=True):
    import pandas as pd
    # 判斷是否傳入測試數據,若沒有傳入則測試數據賦值為訓練數據
    try:
        if predict == None:
            predict = data.copy()
    except Exception:
        pass
    predict = pd.DataFrame(predict)
    # 計算 LOF 離群因子
    predict = localoutlierfactor(data, predict, k)
    if plot == True:
        plot_lof(predict, method)
    # 根據閾值划分離群點與正常點
    outliers = predict[predict['local outlier factor'] > method].sort_values(by='local outlier factor')
    inliers = predict[predict['local outlier factor'] <= method].sort_values(by='local outlier factor')
    return outliers, inliers
import numpy as np
import pandas as pd
import xlrd
# 根據文件位置自行修改
posi = pd.read_excel(r'./已結束項目任務數據.xls')
lon = np.array(posi["任務gps經度"][:])  # 經度
lat = np.array(posi["任務gps 緯度"][:])  # 緯度
A = list(zip(lat, lon))  # 按照緯度-經度匹配

# 獲取任務密度,取第5鄰域,閾值為2(LOF大於2認為是離群值)
outliers1, inliers1 = lof(A, k=5, method = 2)

Alt text

參考鏈接:
https://www.jianshu.com/p/8c5c0c903f27
https://zhuanlan.zhihu.com/p/28178476
異常檢測的幾種方法
https://xz.aliyun.com/t/5378


免責聲明!

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



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