K-means:Elbow 分析
在前面的練習中,你使用樹狀圖(dendrogram)來提出會生成 3 個群集的分群結果。這一題你將利用 k-means 的 elbow 圖,來提出「最佳」的群集數。
本練習屬於課程
R 的叢集分析
練習說明
- 使用
map_dbl()搭配kmeans(),以oes資料在 k 從 1 到 10 的範圍內進行模型訓練,並從每個模型擷取群內平方和總和: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)