R 中 kmeans 的创建预测函数

Creation prediction function for kmean in R

我想创建预测函数来预测观察所属的集群

data(iris)
 mydata=iris
m=mydata[1:4]
train=head(m,100)
xNew=head(m,10)


rownames(train)<-1:nrow(train)

norm_eucl=function(train)
  train/apply(train,1,function(x)sum(x^2)^.5)
m_norm=norm_eucl(train)


result=kmeans(m_norm,3,30)

predict.kmean <- function(cluster, newdata)
{
  simMat <- m_norm(rbind(cluster, newdata),
              sel=(1:nrow(newdata)) + nrow(cluster))[1:nrow(cluster), ]
  unname(apply(simMat, 2, which.max))
}

## assign new data samples to exemplars
predict.kmean(m_norm, x[result$cluster, ], xNew)

报错后

Error in predict.kmean(m_norm, x[result$cluster, ], xNew) : 
  unused argument (xNew)

我知道我在做一些错误的功能,因为我只是在学习做,但我不明白具体在哪里。

我确实想采用apcluster的类似功能(我看过类似的主题,但针对apcluster)

predict.apcluster <- function(s, exemplars, newdata)
{
  simMat <- s(rbind(exemplars, newdata),
              sel=(1:nrow(newdata)) + nrow(exemplars))[1:nrow(exemplars), ]
  unname(apply(simMat, 2, which.max))
}

## assign new data samples to exemplars
predict.apcluster(negDistMat(r=2), x[apres@exemplars, ], xNew)

怎么做?

与其尝试复制某些东西,不如提出我们自己的功能。对于给定的向量 x,我们想要使用一些先验 k-means 输出分配一个集群。鉴于 k-means 算法的工作原理,我们想要的是找到哪个集群的 center 最接近 x。可以这样做

predict.kmeans <- function(x, newdata)
  apply(newdata, 1, function(r) which.min(colSums((t(x$centers) - r)^2)))

也就是说,我们逐行检查 newdata 并计算相应行到每个中心的距离并找到最小的一个。然后,例如,

head(predict(result, train / sqrt(rowSums(train^2))), 3)
# 1 2 3 
# 2 2 2
all.equal(predict(result, train / sqrt(rowSums(train^2))), result$cluster)
# [1] TRUE

这证实了我们的预测函数将所有相同的聚类分配给了训练观察。然后还有

predict(result, xNew / sqrt(rowSums(xNew^2)))
#  1  2  3  4  5  6  7  8  9 10 
#  2  2  2  2  2  2  2  2  2  2 

另请注意,我只是调用 predict 而不是 predict.kmeans。那是因为result属于classkmeans,自动选择了正确的方法。另请注意我如何以矢量化方式规范化数据,而不使用 apply.