基于聚类的异常值检测方法
继上次餐馆老板同学们帮忙对客户数据进行分组后,老板发现部分顾客被划归为某些簇中,而这些顾客是异常的。为此需要对此数据进行异常值检测并删除,然后再对清洗后的数据进行分组。
(1)利用基于对象离群因子法识别离群点
![1aa0abfbe5e34b66b188f2d0cfa67035.png](https://i-blog.csdnimg.cn/blog_migrate/0a905cde2820603de6cd45da7ff5c2bc.png)
(2)利用基于簇的离群因子法识别离群点
![bd03339085f84a06af58608ffb19cd4e.png](https://i-blog.csdnimg.cn/blog_migrate/0e35ad792af43d100791f87678fda2f5.png)
基于近邻的噪声点检测方法
ENN 方法基本思想:针对分类任务的数据集中的某个元素,若其类标签与其 k(一般 k=3)个近邻中多数元素的标签不一致,则认为其是异常对象。顺序
(1)读取“banana.dat”数据文件,并在二维平面上显示其类分布,两种颜色标注;
(2)利用 ENN 方法识别该数据集中的离群点,并一次性全部删除得到新的数据集;
(3)在二维平面上将新数据集进行显示,并观察新、旧数据集对象分布的差异。
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import metrics
import math
data1 = pd.read_csv("C:/Users/wcj770801/Desktop/Python/banana.dat")
data = data1[['At1', 'At2']]
model_kmeans = KMeans(n_clusters=2, random_state=0)
model_kmeans.fit(data)
y_pre = model_kmeans.predict(data)
centers = model_kmeans.cluster_centers_
colors = ['r', 'c', 'b']
plt.figure()
for j in range(2):
index_set = np.where(y_pre==j)
cluster = data.iloc[index_set]
plt.scatter(cluster.iloc[:, 0], cluster.iloc[:, 1], c=colors[j], marker='.')
plt.plot(centers[j][0], centers[j][1], 'o', markerfacecolor=colors[j], markeredgecolor='k', markersize=8) # 画类别中心
plt.show()
def distance(list1, list2):
distance = math.sqrt((list2[0] - list1[0]) ** 2 + (list2[1] - list1[1]) ** 2)
return distance
def OF(data, centers):
center1 = centers[0].tolist()
center2 = centers[1].tolist()
OF = []
for i in range(len(data.index)):
list2 = data.loc[i].tolist()
means = (distance(center1, list2) + distance(center2, list2)) / 2
OF.append(means)
return OF
a = OF(data, centers)
mean = np.mean(a)
std = np.std(a)
li = []
for i in range(len(a)):
if a[i] >= mean + std * 1.285:
li.append(i)
for i in range(len(li)):
data = data.drop([li[i]])
data.reset_index(drop=True, inplace=True)
model_kmeans = KMeans(n_clusters=2, random_state=0)
model_kmeans.fit(data)
y_pre = model_kmeans.predict(data)
centers = model_kmeans.cluster_centers_
colors = ['r', 'c', 'b']
plt.figure()
for j in range(2):
index_set = np.where(y_pre == j)
cluster = data.iloc[index_set]
plt.scatter(cluster.iloc[:, 0], cluster.iloc[:, 1], c=colors[j], marker='.')
plt.plot(centers[j][0], centers[j][1], 'o', markerfacecolor=colors[j], markeredgecolor='k', markersize=8) # 画类别中心
plt.show()