r - R中聚类中心与异常值之间的距离
问题描述
我已经用 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 的绝对初学者,不知道如何解决这个问题。
解决方案
在这种情况下,有一个方便的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
只要异常值和聚类的数量合理,就应该具有良好的性能。
推荐阅读
- php - laravel 5.5 雄辩的查询构建器在使用查询字符串存储 url 时构建错误的查询
- python - 在哪里可以找到 DRF 历史文档?
- windows-installer - 如何使用 Microsoft Visual Studio 安装程序项目构建新版本的 exe
- linux - 排序命令不适用于大文件
- javascript - 继承了一个参考 fast.fonts.net 的网站——它是什么?
- firebase - Cloud Firestore:如何将文档中的字段设置为空
- c# - TFS MSBuild not restoring nugets for websites in solution
- html - 保持容器固定并在窗口调整大小时显示水平滚动条
- verilog - “包含”和“定义”是什么意思?他们做什么?
- java - 如何提取列表
来自 HashMap 使用流