我希望你能帮助我解决我的问题。我正在尝试使用 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)
但是如何使用相对距离而不是绝对距离来查找异常值呢?
您只需要计算每个观察值与其聚类的平均距离。您已经有了这些距离,因此您只需对它们进行平均即可。然后剩下的就是简单的索引除法:
# 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)