【问题标题】:Distance between cluster center and outliers in RR中聚类中心与异常值之间的距离
【发布时间】:2018-09-11 12:45:31
【问题描述】:

我已经使用 R(基于 kmeans)构建了一个聚类模型,并希望通过找到异常值与聚类中心之间的最小距离来对异常值进行分类。我要使用的数据框如下所示:

DF_OUTLIERS

[Product]  [Sales] [Usage]
1   100 1000   
2   200 2000  
3   300 3000  
4   200 4000   
5   100 5000

DF_CLUSTER

[Cluster] [Center_Sales] [Center_Usage]
1    120        1500  
2    220        2400 
3    150        3900    
4    140        4900

目标表应如下所示:

[Product]   [Sales]     [Usage]     [Cluster] 
1       100     1000        ???
2       200     2000        ???
3       300     3000        ???
4       200     4000        ???
5       100     5000        ???

要计算距离我想使用欧几里得距离的标准公式:

sqrt((Sales -  Center_Sales)^2 + (Usage -  Center_Usage)^2))

我最大的问题是开发一个函数,它可以为每一行找到所有集群中的最小值,而无需为每个集群添加一个新列到目标 df。我想对于一个有经验的程序员来说这是一项容易的任务,但我是 R 的绝对初学者,不知道如何解决这个问题。

【问题讨论】:

  • 欢迎来到 SO!您能否使用dput(your_data) 发布一些数据或一些与您类似的虚假数据?
  • 我生成了一些假数据。如何将文件添加到我的帖子中?

标签: r cluster-analysis


【解决方案1】:

有一个方便的which.min 函数在这种情况下很有用。

outliers<-read.table(header=TRUE, text="Product  Sales Usage
1   100 1000   
2   200 2000  
3   300 3000  
4   200 4000   
5   100 5000")

clusters<-read.table(header=TRUE, text="Cluster Center_Sales Center_Usage
1    120        1500  
2    220        2400 
3    150        3900    
4    140        4900")

answer<-sapply(1:nrow(outliers), function(x) {
  #find the distance for the outlier to every cluster
  distance<-sqrt((outliers$Sales[x] -  clusters$Center_Sales)^2 + 
                   (outliers$Usage[x] -  clusters$Center_Usage)^2)
  #find the index of the shortest distance and return
  which.min(distance)
})

answer
#[1] 1 2 2 3 4
outliers$cluster<-answer

只要异常值和聚类的数量合理,性能应该不错。

【讨论】:

  • 这个功能正是我想要的。谢谢!
猜你喜欢
  • 2017-10-26
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2020-12-25
  • 2018-08-07
相关资源
最近更新 更多