R聚类分析:K-means聚类
掌握K-means聚类算法的原理与R实现,学习确定最佳聚类数。 · 难度:入门 · +15XP
K-means聚类概述
K-means将数据划分为K个簇,使得每个样本到其簇中心的距离平方和最小。适用于连续型数值数据,需预先指定K值。
1. 数据准备
data(iris)
X <- iris[,1:4] # 使用数值列2. 执行K-means
set.seed(123)
km <- kmeans(X, centers = 3, nstart = 25)
print(km$cluster)
print(km$centers)3. 确定最佳K值:肘部法
wss <- sapply(1:10, function(k){ kmeans(X, k, nstart=25)$tot.withinss })
plot(1:10, wss, type = 'b', xlab = 'K', ylab = 'Total WSS')4. 可视化聚类结果
library(ggplot2)
df <- data.frame(X, cluster = as.factor(km$cluster))
ggplot(df, aes(x = Petal.Length, y = Petal.Width, color = cluster)) + geom_point()| 参数 | 说明 |
|---|---|
| centers | 簇数K |
| nstart | 随机初始化的次数,选最优结果 |
| tot.withinss | 总簇内平方和 |
练习提示:使用USArrests数据集进行K-means聚类(K=4),并用fviz_cluster()(factoextra包)可视化。