開始使用免費開始

許多 k、許多模型

雖然 lineup 資料集的 k 是已知的,但多數時候最佳的群集數並不清楚,需要先估計。

在這個練習中,你會使用 purrr 函式庫的 map_dbl(),以 k 從 1 到 10 的各種值來執行 k-means,並從每個模型擷取「群內平方和總和(total within-cluster sum of squares)」這個指標。這會是你視覺化肘部圖(elbow plot)的第一步。

本練習屬於課程

R 的叢集分析

檢視課程

練習說明

  • 使用 map_dbl() 搭配 kmeans(),以 lineup 資料在 k 從 1 到 10 的範圍建立模型,並從每個模型擷取「群內平方和總和」:model$tot.withinss。 將得到的向量儲存為 tot_withinss
  • 建立新的資料框 elbow_df,其中包含各個 k 的值,以及對應的「群內平方和總和」向量。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

library(purrr)

# 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 = ___
)
編輯並執行程式碼