R聚类分析

实例1: 基于随机生成序列的动态聚类

set.seed(1234)
dat<-rbind(matrix(rnorm(100,mean=0,sd=0.2),ncol=2),
           matrix(rnorm(100,mean=1,sd=0.3),ncol=2))
colnames(dat)<-c("x","y")
plot(dat)

       上图中很明显点大致地分为两类,下面对其进行K-means聚类:

(kmeans.1<-kmeans(dat,2))   # 将原始数据聚为两类
-------结果-------
K-means clustering with 2 clusters of sizes 50, 50 
Cluster means:
           x          y
1 -0.0906106 0.02790591
2  1.0059934 1.01875248
Clustering vector:
 [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 [29] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
 [57] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 [85] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
Within cluster sum of squares by cluster:
[1] 3.643813 9.488740
(between_SS / total_SS =  80.6 %)

   绘制聚类结果图,并标注出类质心点:

plot(dat,col=kmeans.1$cluster,main="聚成两类")
points(kmeans.1$centers,col=3:4,pch=8,cex=2)

·   此外,可以尝试聚成三类:

(kmeans.2<-kmeans(dat,3))
plot(dat,col=kmeans.2$cluster,main="聚成三类")
points(kmeans.2$centers,col=3:5,pch=8,cex=2)
----------结果------------
K-means clustering with 3 clusters of sizes 31, 50, 19
Within cluster sum of squares by cluster:
[1] 3.439893 3.643813 2.320827
(between_SS / total_SS =  86.1 %)

   两种聚类结果都合理,为比较两者的优劣,引入新的指标进行衡量:

\bg_white \frac{betweenss}{k-1}/\frac{tot.withiness}{n-k}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值