python 離群點檢測


 1 import numpy as np
 2 import pandas as pd
 3 from sklearn.cluster import KMeans
 4 import matplotlib.pyplot as mp
 5 
 6 
 7 def get_data_zs(inputfile):
 8     data = pd.read_excel(inputfile, index_col='Id', encoding='gb18030')
 9     data_zs = 1.0 * (data - data.mean()) / data.std()
10     return data, data_zs
11 
12 
13 def model_data_zs(data, k, b):
14     model = KMeans(n_clusters=k, n_jobs=4, max_iter=b)
15     model.fit(data_zs)
16 
17     # 標准化數據及其類別
18     r = pd.concat(
19         [data_zs, pd.Series(model.labels_, index=data.index)], axis=1)
20     # print(r.head())
21     # 每個樣本對應的類別
22     r.columns = list(data.columns) + [u'聚類類別']  # 重命名表頭
23     return model, r, k
24 
25 
26 def make_norm(model, k):
27     norm = []
28     for i in range(k):
29         norm_tmp = r[['R', 'F', 'M']][
30             r[u'聚類類別'] == i] - model.cluster_centers_[i]
31         norm_tmp = norm_tmp.apply(np.linalg.norm, axis=1)  # 求出絕對距離
32         norm.append(norm_tmp / norm_tmp.median())  # 求相對距離並添加
33     norm = pd.concat(norm)
34     return norm
35 
36 
37 def draw_discrete_point(threshold):
38     mp.rcParams['font.sans-serif'] = ['SimHei']
39     mp.rcParams['axes.unicode_minus'] = False
40     norm[norm <= threshold].plot(style='go')  # 正常點
41 
42     discrete_points = norm[norm > threshold]  # 離散點閾值
43     discrete_points.plot(style='rs')
44     # print(discrete_points)
45 
46     for i in range(len(discrete_points)):  # 離群點做標記
47         id = discrete_points.index[i]
48         n = discrete_points.iloc[i]
49         mp.annotate('(%s,%0.2f)' % (id, n), xy=(id, n), xytext=(id, n))
50     mp.xlabel(r'編號')
51     mp.ylabel(r'相對距離')
52     mp.show()
53 
54 if __name__ == '__main__':
55     inputfile = 'data/consumption_data.xls'
56     threshold = 2 # 離散點閾值
57     k = 3 # 聚類類別
58     b = 500 # 聚類最大循環次數
59     data, data_zs = get_data_zs(inputfile)
60     model, r, k = model_data_zs(data, k, b)
61     norm = make_norm(model, k)
62     draw_discrete_point(threshold)
63     print('All Done')

 

顯示結果:

 


免責聲明!

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



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