【发布时间】:2017-06-14 06:01:10
【问题描述】:
我正在尝试在 R 中编写我自己的第一个 kmeans 算法。我是这个领域的新手,所以请不要因为没有看到明显的东西而评判我。
在当前状态下,该算法采用两个向量x、y,计算每个数据点到集群中心的距离,并分配从其中心到数据点距离最小的集群。当分配没有变化时算法停止,因此聚类中心也没有变化。
# Sample data
set.seed(100)
xval <- rnorm(12, mean = rep(1:3, each = 4), sd = 0.2)
yval <- rnorm(12, mean = rep(c(1,2,1), each = 4), sd = 0.2)
# Kmeans function
kclus <- function(x, y, nclus) {
# start with random cluster centers
xcen <- runif(n = nclus, min = min(x), max = max(x))
ycen <- runif(n = nclus, min = min(y), max = max(y))
# data points and cluster assignment in "data"
# cluster coordinates in "clus"
data <- data.frame(xval = x, yval = y, clus = NA)
clus <- data.frame(name = 1:nclus, xcen = xcen, ycen = ycen)
finish <- FALSE
while(finish == FALSE) {
# assign cluster with minimum distance to each data point
for(i in 1:length(x)) {
dist <- sqrt((x[i]-clus$xcen)^2 + (y[i]-clus$ycen)^2)
data$clus[i] <- which.min(dist)
}
xcen_old <- clus$xcen
ycen_old <- clus$ycen
# calculate new cluster centers
for(i in 1:nclus) {
clus[i,2] <- mean(subset(data$xval, data$clus == i))
clus[i,3] <- mean(subset(data$yval, data$clus == i))
}
# stop the loop if there is no change in cluster coordinates
if(identical(xcen_old, clus$xcen) & identical(ycen_old, clus$ycen)) finish <- TRUE
}
data
}
# apply kmeans function to sample data
cluster <- kclus(xval, yval, 4)
# plot the result
ggplot(cluster, aes(xval, yval, color = as.factor(clus))) + geom_point()
到目前为止,这工作相对较好。但我不知道如何将算法强制到特定数量的集群。它已经在我的kclus()函数中作为参数nclus实现了,但我不知道如何使用它。
对于给定的样本数据,算法只给了我三个集群。我要逼他把四簇还给我。
这里有人可以给我建议吗?
非常感谢, 马库斯
【问题讨论】:
标签: r algorithm machine-learning data-mining k-means