Skip to main content
 首页 » 人工智能

使用R kmeans 算法实现异常检测

2022年07月19日141powertoolsteam

kmeans 采用计算数据每个元素到聚集中心点的距离方式判断异常值。
利用R提供的kmeans函数把数据聚集为几个簇,然后再计算每个元素至簇中心的距离,最后选择最远距离的几个点,视为异常值。

准备数据

set.seed(97) 
test <- as_tibble(runif(100)*10) %>% mutate(id=row_number(), .before = "value") 
head(test, 10) 
 
# 增加几个异常值 
test %>%  
  mutate(value=ifelse(id %in% sample(1:100,5),sample(10:20,5),value)) -> test 
summary(test) 

上面代码首先生成100均匀分布的测试数据,然后转成tibble类型,接着增加5个异常值用于演示。

kmeans 实现

## 聚类为2个簇 
km <- kmeans(test, centers=2) 
## 获得每个点对于的中心点 
centers=km$centers[km$cluster,]  
# km$centers 
#     id    value 
# 1 75.5 5.452826 
# 2 25.5 4.488004 
head(centers) 
 #     id    value 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
 
# 计算每个点到中心点的距离 
distance <- sqrt((test$value-centers[,2])^2) 
  
 ## 按距离降序排序,获取最远的5个带你 
ordered <- order(distance, decreasing = T) 

km$cluster 把test转成向量,分别为1和2,表示为属于那个簇。km$centers 为每个簇的中心点。

画图

下面我们通过ggplot2 画原始数据并标出异常值。

## 取前5个点的序号,并获取对应的值,用于后面画图 
out_ids <- head(ordered, 5) 
outs <- test %>% filter(id %in% out_ids) 
outs 
#      id   value 
#   <int>   <dbl> 
# 1    26 16      
# 2    52 20      
# 3    74 19      
# 4    82  0.0202 
# 5    86 16    
# 首先用点线图画原始数据,然后以叠加方式标出异常值 
ggplot(test, aes(x=id, y=value)) + geom_line(aes(colour=I("blue"))) + 
    geom_point(data=outs, aes(x=id, y=value, colour="red")) 

在这里插入图片描述

完整代码

library(dplyr) 
library(ggplot2) 
library(tibble) 
 
## 生成示例数据 
set.seed(97) 
test <- as_tibble(runif(100)*10) %>% mutate(id=row_number(), .before = "value") 
head(test, 10) 
 
# 增加几个异常值 
test %>%  
  mutate(value=ifelse(id %in% sample(1:100,5),sample(10:20,5),value)) -> test 
summary(test) 
 
# test[sample(1:100,5)] <- sample(10:20,5) 
 
# 画出数据的分布情况 
# test是向量,这里直接使用qplot函数 
# ggplot(test, aes(x=id, y=value)) + geom_line(aes(colour=I("blue"))) 
# qplot(x=1:length(test), y=test, geom = "line", colour = I("blue")) 
  
km <- kmeans(test, centers=2) 
centers=km$centers[km$cluster,]  
# km$centers 
#     id    value 
# 1 75.5 5.452826 
# 2 25.5 4.488004 
 
head(centers) 
 
#     id    value 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
# 2 25.5 4.488004 
  
distance <- sqrt((test$value-centers[,2])^2) 
  
ordered <- order(distance, decreasing = T) 
out_ids <- head(ordered, 5) 
#   
# print(outs) 
# print(test[outs]) 
 
outs <- test %>% filter(id %in% out_ids) 
outs 
#      id   value 
#   <int>   <dbl> 
# 1    26 16      
# 2    52 20      
# 3    74 19      
# 4    82  0.0202 
# 5    86 16    
 
# plot(test, pch=16, col="blue") 
ggplot(test, aes(x=id, y=value)) + geom_line(aes(colour=I("blue"))) + 
    geom_point(data=outs, aes(x=id, y=value, colour="red")) 

因为生成的示例数据为向量,如果直接使用向量画图,则直接使用 qplot函数,x轴为序号,通过1:length(test_vec) 获得:
qplot(x=1:length(test_vec), y=test, geom = "line", colour = I("blue"))

两者的区别如下:

# test 为tibble 
# ggplot(test, aes(x=id, y=value)) + geom_line(aes(colour=I("blue"))) 
# test为向量 
# qplot(x=1:length(test), y=test, geom = "line", colour = I("blue")) 

本文参考链接:https://blog.csdn.net/neweastsun/article/details/121876117