k-表示R中的返回值

时间:2011-12-26 16:29:49

标签: r k-means least-squares

我在R中使用kmeans()函数,我很好奇返回对象的 totss tot.withinss 属性之间的区别是什么。从文档中他们似乎返回相同的东西,但在我的数据集上应用totss的值是66213.63,而tot.withinss的值是6893.50。 如果您熟悉mroe细节,请告诉我。 谢谢!

的Marius。

2 个答案:

答案 0 :(得分:19)

给定平方和betweenss与每个聚类withinss的平方和内的向量之间的公式:

totss = tot.withinss + betweenss
tot.withinss = sum(withinss)

例如,如果只有一个群集,那么betweenss将是0,则withinsstotss = tot.withinss = withinss中只会有一个群组。

为了进一步说明,我们可以根据群集分配自行计算这些不同的数量,这可能有助于阐明它们的含义。考虑x中示例中的数据cl$cluster和群集分配help(kmeans)。定义平方和函数如下 - 这将从该列中减去每列x的平均值,然后减去剩余矩阵的每个元素的平方和:

# or ss <- function(x) sum(apply(x, 2, function(x) x - mean(x))^2)
ss <- function(x) sum(scale(x, scale = FALSE)^2)

然后我们有以下内容。注意cl$centers[cl$cluster, ]是拟合值,即它是一个矩阵,每个点有一行,这样第i行就是第i个点所属的簇的中心。

example(kmeans) # create x and cl

betweenss <- ss(cl$centers[cl$cluster,]) # or ss(fitted(cl))

withinss <- sapply(split(as.data.frame(x), cl$cluster), ss)
tot.withinss <- sum(withinss) # or  resid <- x - fitted(cl); ss(resid)

totss <- ss(x) # or tot.withinss + betweenss

cat("totss:", totss, "tot.withinss:", tot.withinss, 
  "betweenss:", betweenss, "\n")

# compare above to:

str(cl)

编辑:

由于此问题已得到解答,因此R添加了其他类似的kmeans示例(example(kmeans))和新的fitted.kmeans方法,现在我们将展示拟合方法如何适用于上述评论尾随代码行。

答案 1 :(得分:0)

我认为您在文档中发现了一个错误...其中说:

withinss     The within-cluster sum of squares for each cluster.
totss        The total within-cluster sum of squares.
tot.withinss     Total within-cluster sum of squares, i.e., sum(withinss).

如果您在帮助页面示例中使用示例数据集:

> kmeans(x,2)$tot.withinss
[1] 15.49669
> kmeans(x,2)$totss
[1] 65.92628
> kmeans(x,2)$withinss
[1] 7.450607 8.046079

我认为有人应该向r-devel邮件列表写一个请求,要求修改帮助页面。如果你不愿意,我愿意这样做。