使用k-means算法检测异常值

时间:2014-05-07 11:18:29

标签: r k-means outliers

我希望你能解决我的问题。我试图使用kmeans算法检测异常值。首先,我执行算法并选择那些可能与群集中心距离很远的异常值。而不是使用绝对距离我想使用相对距离,即对象与聚类中心的绝对距离的比率以及聚类的所有对象与其聚类中心的平均距离。基于绝对距离的离群值检测代码如下:

# remove species from the data to cluster
iris2 <- iris[,1:4]
kmeans.result <- kmeans(iris2, centers=3)
# cluster centers
kmeans.result$centers
# calculate distances between objects and cluster centers
centers <- kmeans.result$centers[kmeans.result$cluster, ]
distances <- sqrt(rowSums((iris2 - centers)^2))
# pick top 5 largest distances
outliers <- order(distances, decreasing=T)[1:5]
# who are outliers
print(outliers)

但是如何使用相对而不是绝对距离来查找异常值?

1 个答案:

答案 0 :(得分:8)

您只需计算每个观察距其群集的平均距离。你已经有了那些距离,所以你只需要平均它们。然后其余的是简单的索引划分:

# calculate mean distances by cluster:
m <- tapply(distances, kmeans.result$cluster,mean)

# divide each distance by the mean for its cluster:
d <- distances/(m[kmeans.result$cluster])

你的异常值:

> d[order(d, decreasing=TRUE)][1:5]
       2        3        3        1        3 
2.706694 2.485078 2.462511 2.388035 2.354807