R聚类分析
学习K-means和层次聚类,使用ggplot2进行聚类可视化 · 难度:入门 · +15XP
聚类分析:发现数据中的自然分组
聚类是一种无监督学习方法,将相似样本归为一组。本节介绍K-means和层次聚类。
1. K-means聚类
需要指定聚类数k,算法迭代优化簇内距离平方和。
data(iris)
set.seed(123)
kmeans_result <- kmeans(iris[,1:4], centers = 3, nstart = 25)
kmeans_result$cluster # 每个样本的簇标签2. 肘部法则选择k
wss <- numeric(10)
for(k in 1:10){
wss[k] <- kmeans(iris[,1:4], centers=k, nstart=10)$tot.withinss
}
plot(1:10, wss, type='b', xlab='k', ylab='总簇内离差平方和')3. 层次聚类
dist_mat <- dist(iris[,1:4], method='euclidean')
hclust_result <- hclust(dist_mat, method='ward.D2')
plot(hclust_result, labels=iris$Species, main='树状图')4. 可视化聚类结果
library(ggplot2)
iris$cluster <- as.factor(kmeans_result$cluster)
ggplot(iris, aes(Petal.Length, Petal.Width, color=cluster)) + geom_point()聚类方法对比:
| 方法 | 优点 | 缺点 |
|---|---|---|
| K-means | 速度快,适合大数据 | 需指定k,对异常值敏感 |
| 层次聚类 | 不需指定k,树状图直观 | 计算复杂度高 |
练习提示:对mtcars数据集做K-means聚类(k=3),并绘制散点图按簇着色。