R语言聚类分析


#特征距离
data(iris)
str(iris)     #查看数据结构,包含多少个体,多少变量,变量类别
table(iris$Species)   #频数分布
library(ggplot2)  #加载ggplot2包
ggplot(data=iris)+geom_point(aes(x=Sepal.Length,y=Sepal.Width,
                                 color=Species,shape=Species),position = "jitter")
x=iris[,-5]   #去掉第五列分类变量species
head(x)  #查看前6个个体的值
x=scale(x)    #标准化
head(x)
dist.iris=dist(x,method = "euclidean") #计算距离
head(dist.iris)
dmat=as.matrix(dist.iris)    #聚类矩阵
dmat
round(dmat[1:15,1:5],2)   #保留两位小数  
par(mar=c(1,2,1,2))   #图形边界设置
image(t(dmat[nrow(dmat):1,]),axes=FALSE,zlim=c(-2,7),col=rainbow(21))  #矩阵网格图
#K均值聚类
kc=kmeans(x,3)  #k均值聚类,聚3类
table(iris$Species,kc$cluster)   #混淆矩阵
kc$centers    #聚类中心
kc$size    #查看各族的大小
#层次聚类
clusters=hclust(dist(iris[,1:4]))  #层次聚类
plot(clusters)  #树状图
clusterCut=cutree(clusters,3)  #指定聚成3类,默认采用全联动度量距离
table(clusterCut,iris$Species)  #混淆矩阵
clusters1=hclust(dist(iris[,1:4]),method="average")  #全联动效果不太好,使用平均联动距离
plot(clusters1)
clusterCut1=cutree(clusters1,3)   #聚为三类
table(clusterCut1,iris$Species)   #混淆矩阵
#密度聚类
install.packages("fpc")
library(fpc)
install.packages("mlbench")
library(mlbench)
pts=mlbench::mlbench.cassini(n=600,relsize=c(3,2,1))#产生3个类别的样本点
plot(pts)
cluster.density=dbscan(data=pts$x,eps=0.2,MinPts = 5,method="hybrid") #取邻域半径为0.2,最小样本点为5,进行密度聚类
cluster.density
plot.dbscan(cluster.density,pts$x)
cluster.density1=dbscan(data=pts$x,eps=0.22,MinPts = 5,method="hybrid") #改变邻域半径
cluster.density1
plot.dbscan(cluster.density1,pts$x)
cluster.density1$cluster  #聚类结果
 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈伦2019

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值