京公网安备 11010802034615号
经营许可证编号:京B2-20210330
R语言学习笔记之聚类分析
使用k-means聚类所需的包:
factoextra
cluster #加载包
library(factoextra)
library(cluster)l
#数据准备
使用内置的R数据集USArrests
#load the dataset
data("USArrests")
#remove any missing value (i.e, NA values for not available)
#That might be present in the data
USArrests <- na.omit(USArrests)#view the first 6 rows of the data
head(USArrests, n=6)
在此数据集中,列是变量,行是观测值
在聚类之前我们可以先进行一些必要的数据检查即数据描述性统计,如平均值、标准差等
desc_stats <- data.frame( Min=apply(USArrests, 2, min),#minimum
Med=apply(USArrests, 2, median),#median
Mean=apply(USArrests, 2, mean),#mean
SD=apply(USArrests, 2, sd),#Standard deviation
Max=apply(USArrests, 2, max)#maximum
)
desc_stats <- round(desc_stats, 1)#保留小数点后一位head(desc_stats)
变量有很大的方差及均值时需进行标准化
df <- scale(USArrests)
#数据集群性评估
使用get_clust_tendency()计算Hopkins统计量
res <- get_clust_tendency(df, 40, graph = TRUE)
res$hopkins_stat
## [1] 0.3440875
#Visualize the dissimilarity matrix
res$plot
![]()
Hopkins统计量的值<0.5,表明数据是高度可聚合的。另外,从图中也可以看出数据可聚合。
#估计聚合簇数
由于k均值聚类需要指定要生成的聚类数量,因此我们将使用函数clusGap()来计算用于估计最优聚类数。函数fviz_gap_stat()用于可视化。
set.seed(123)
## Compute the gap statistic
gap_stat <- clusGap(df, FUN = kmeans, nstart = 25, K.max = 10, B = 500)
# Plot the result
fviz_gap_stat(gap_stat)
图中显示最佳为聚成四类(k=4)
#进行聚类
set.seed(123)
km.res <- kmeans(df, 4, nstart = 25)
head(km.res$cluster, 20)
![]()
# Visualize clusters using factoextra
fviz_cluster(km.res, USArrests)
#检查cluster silhouette图
Recall that the silhouette measures (SiSi) how similar an object ii is to the the other objects in its own cluster versus those in the neighbor cluster. SiSi values range from 1 to - 1:
A value of SiSi close to 1 indicates that the object is well clustered. In the other words, the object ii is similar to the other objects in its group.
A value of SiSi close to -1 indicates that the object is poorly clustered, and that assignment to some other cluster would probably improve the overall results.
sil <- silhouette(km.res$cluster, dist(df))
rownames(sil) <- rownames(USArrests)
head(sil[, 1:3])
![]()
#Visualize
fviz_silhouette(sil)
图中可以看出有负值,可以通过函数silhouette()确定是哪个观测值
neg_sil_index <- which(sil[, "sil_width"] < 0)
sil[neg_sil_index, , drop = FALSE]
## cluster neighbor sil_width
## Missouri 3 2 -0.07318144
#eclust():增强的聚类分析
与其他聚类分析包相比,eclust()有以下优点:
简化了聚类分析的工作流程
可以用于计算层次聚类和分区聚类
eclust()自动计算最佳聚类簇数。
自动提供Silhouette plot
可以结合ggplot2绘制优美的图形
#使用eclust()的K均值聚类
# Compute k-means
res.km <- eclust(df, "kmeans")
![]()
# Gap statistic plot
fviz_gap_stat(res.km$gap_stat)
![]()
# Silhouette plotfviz_silhouette(res.km)
## cluster size ave.sil.width
## 1 1 13 0.31
## 2 2 29 0.38
## 3 3 8 0.39
#使用eclust()的层次聚类
# Enhanced hierarchical clustering
res.hc <- eclust(df, "hclust") # compute hclust
fviz_dend(res.hc, rect = TRUE) # dendrogam
![]()
#下面的R代码生成Silhouette plot和分层聚类散点图。
fviz_silhouette(res.hc) # silhouette plot
## cluster size ave.sil.width
## 1 1 19 0.26
## 2 2 19 0.28
## 3 3 12 0.43
![]()
fviz_cluster(res.hc) # scatter plot
#Infos
This analysis has been performed using R software (R version 3.3.2)
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在机器学习领域,“分类模型” 是解决 “类别预测” 问题的核心工具 —— 从 “垃圾邮件识别(是 / 否)” 到 “疾病诊断(良性 ...
2025-11-06在数据分析中,面对 “性别与购物偏好”“年龄段与消费频次”“职业与 APP 使用习惯” 这类成对的分类变量,我们常常需要回答: ...
2025-11-06在 CDA(Certified Data Analyst)数据分析师的工作中,“可解释性建模” 与 “业务规则提取” 是核心需求 —— 例如 “预测用户 ...
2025-11-06在分类变量关联分析中(如 “吸烟与肺癌的关系”“性别与疾病发病率的关联”),卡方检验 P 值与 OR 值(比值比,Odds Ratio)是 ...
2025-11-05CDA 数据分析师的核心价值,不在于复杂的模型公式,而在于将数据转化为可落地的商业行动。脱离业务场景的分析只是 “纸上谈兵” ...
2025-11-05教材入口:https://edu.cda.cn/goods/show/3151 “纲举目张,执本末从。” 若想在数据分析领域有所收获,一套合适的学习教材至 ...
2025-11-05教材入口:https://edu.cda.cn/goods/show/3151 “纲举目张,执本末从。” 若想在数据分析领域有所收获,一套合适的学习教材至 ...
2025-11-04【2025最新版】CDA考试教材:CDA教材一级:商业数据分析(2025)__商业数据分析_cda教材_考试教材 (cdaglobal.com) ...
2025-11-04在数字化时代,数据挖掘不再是实验室里的技术探索,而是驱动商业决策的核心能力 —— 它能从海量数据中挖掘出 “降低成本、提升 ...
2025-11-04在 DDPM(Denoising Diffusion Probabilistic Models)训练过程中,开发者最常困惑的问题莫过于:“我的模型 loss 降到多少才算 ...
2025-11-04在 CDA(Certified Data Analyst)数据分析师的工作中,“无监督样本分组” 是高频需求 —— 例如 “将用户按行为特征分为高价值 ...
2025-11-04当沃尔玛数据分析师首次发现 “啤酒与尿布” 的高频共现规律时,他们揭开了数据挖掘最迷人的面纱 —— 那些隐藏在消费行为背后 ...
2025-11-03这个问题精准切中了配对样本统计检验的核心差异点,理解二者区别是避免统计方法误用的关键。核心结论是:stats.ttest_rel(配对 ...
2025-11-03在 CDA(Certified Data Analyst)数据分析师的工作中,“高维数据的潜在规律挖掘” 是进阶需求 —— 例如用户行为包含 “浏览次 ...
2025-11-03在 MySQL 数据查询中,“按顺序计数” 是高频需求 —— 例如 “统计近 7 天每日订单量”“按用户 ID 顺序展示消费记录”“按产品 ...
2025-10-31在数据分析中,“累计百分比” 是衡量 “部分与整体关系” 的核心指标 —— 它通过 “逐步累加的占比”,直观呈现数据的分布特征 ...
2025-10-31在 CDA(Certified Data Analyst)数据分析师的工作中,“二分类预测” 是高频需求 —— 例如 “预测用户是否会流失”“判断客户 ...
2025-10-31在 MySQL 实际应用中,“频繁写入同一表” 是常见场景 —— 如实时日志存储(用户操作日志、系统运行日志)、高频交易记录(支付 ...
2025-10-30为帮助教育工作者、研究者科学分析 “班级规模” 与 “平均成绩” 的关联关系,我将从相关系数的核心定义与类型切入,详解 “数 ...
2025-10-30对 CDA(Certified Data Analyst)数据分析师而言,“相关系数” 不是简单的数字计算,而是 “从业务问题出发,量化变量间关联强 ...
2025-10-30