k均值聚类_异常检测
- 先来张图,快速理解
- 正常数据应该分布在两个簇中
- 异常数据,距离两个簇都很远
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
# 正常数据分为两个簇
normal_data1 = np.random.normal(0, 1, (20, 2))
normal_data2 = np.random.normal(10, 1, (20, 2))
# 异常数据两个点
anomalies = np.array([[1, 10],[10,0] ])
data = np.vstack([normal_data1,normal_data2, anomalies])
# 使用K均值聚类算法将数据分为K个簇(K=2)
kmeans = KMeans(n_clusters=2,n_init=10)
kmeans.fit(data)
# 计算每个数据点到其所属簇中心的距离
distances = cdist(data, kmeans.cluster_centers_, 'euclidean')
min_distances = np.min(distances, axis=1)
# 设置阈值并检测异常值
threshold = 5
outliers = data[min_distances > threshold]
# 输出结果
print("Outliers:")
print(outliers)
# 绘制数据的散点图
plt.scatter(normal_data1[:, 0], normal_data1[:, 1])
plt.scatter(normal_data2[:, 0], normal_data2[:, 1])
plt.scatter(anomalies[:, 0], anomalies[:, 1])
plt.show()
标签:__,distances,plt,normal,均值,算法,聚类,np,10
From: https://www.cnblogs.com/zhuoss/p/17484500.html