开始使用免费开始使用

K-means:肘部法分析

在前面的练习中,您使用树状图提出了一个将数据分成 3 个簇的聚类方案。本练习中,您将利用 k-means 的肘部图来提出"最佳"的聚类数。

本练习是课程的一部分

R 中的聚类分析

查看课程

练习说明

  • 使用 map_dbl()k 取 1 到 10 的取值,基于 oes 数据运行 kmeans(),并从每个模型中提取簇内离差平方和总和(total within-cluster sum of squares):model$tot.withinss。将得到的向量保存为 tot_withinss
  • 构建一个新的数据框 elbow_df,包含 k 的取值以及对应的簇内离差平方和总和向量。
  • 使用 elbow_df 中的数值绘制折线图,展示 k簇内离差平方和总和之间的关系。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Use map_dbl to run many models with varying value of k (centers)
tot_withinss <- map_dbl(1:10,  function(k){
  model <- kmeans(x = ___, centers = ___)
  model$tot.withinss
})

# Generate a data frame containing both k and tot_withinss
elbow_df <- data.frame(
  k = ___,
  tot_withinss = ___
)

# Plot the elbow plot
ggplot(elbow_df, aes(x = ___, y = ___)) +
  geom_line() +
  scale_x_continuous(breaks = 1:10)
编辑并运行代码