【问题标题】:Compute between clusters sum of squares (BCSS) and total sum of squares manually (clustering in R)手动计算聚类平方和 (BCSS) 和总平方和(R 中的聚类)
【发布时间】:2021-10-13 07:08:49
【问题描述】:

我正在尝试仅根据数据和集群分配手动检索与集群解决方案相关的一些统计信息。

例如,kmeans() 计算之间的簇和平方和。

data <- iris[1:4]
  
fit <- kmeans(data, 3)
clusters <- fit$cluster

fit$betweenss
#> [1] 602.5192
fit$totss
#> [1] 681.3706

reprex package (v2.0.1) 于 2021-08-09 创建

我想在不调用kmeans 的情况下恢复这些索引,只使用dataclusters 的向量(这样我就可以将其应用于任何聚类解决方案)。

感谢this other post,我设法检索了 within 簇的平方和,而我现在只是缺少中间和总数。对他们来说,另一篇文章说:

总平方和,sum_x sum_y ||x-y||² 是常数。

总平方和可以通过方差简单地计算出来。

如果现在减去 x 和 y 属于同一个簇的簇内平方和,则簇间平方和仍然存在。

但我不知道如何将其翻译成 R...感谢任何帮助。

【问题讨论】:

    标签: r cluster-analysis k-means hierarchical-clustering


    【解决方案1】:

    这将计算总平方和 (TSS)、平方内和 (WSS) 和平方和之间 (BSS)。你真的只需要前两个,因为 BSS = TSS - WSS:

    set.seed(42)    # Set seed since kmeans uses a random start.
    fit <- kmeans(data, 3)
    clusters <- fit$cluster
    
    # Subtract each value from the grand mean and get the number of observations in each cluster.
    data.cent <- scale(data, scale=FALSE)
    nrows <- table(clusters)
    
    (TSS <- sum(data.cent^2))
    # [1] 681.3706
    (WSS <- sapply(split(data, clusters), function(x) sum(scale(x, scale=FALSE)^2)))
    #        1        2        3 
    # 15.15100 39.82097 23.87947 
    (BSS <- TSS - sum(WSS))
    # [1] 602.5192
    # Compute BSS directly
    gmeans <- sapply(split(data, clusters), colMeans)
    means <- colMeans(data)
    (BSS <- sum(colSums((gmeans - means)^2) * nrows))
    # [1] 602.5192
    

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 2018-05-04
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多