r语言不同聚类算法比较代码 下载本文

内容发布更新时间 : 2024/5/18 5:51:45星期一 下面是文章的全部内容请认真阅读。

秋雨氤氲.R

Administrator Wed Jun 14 09:22:27 2017

#生成两类随机数合并

y=rbind(matrix(rnorm(10000,mean=2,sd=0.3),ncol=10),matrix(rnorm(10000,mean=1,sd=0.7),ncol=10))

colnames(y)=c(paste(\,1:10))#变量名

#查看数据 head(y)

## y 1 y 2 y 3 y 4 y 5 y 6 y 7 ## [1,] 2.061236 2.558978 1.836307 1.571482 1.414348 1.873016 1.834938 ## [2,] 2.096080 1.965268 1.905418 1.949796 1.841915 1.940653 2.100772 ## [3,] 2.354531 1.798288 2.081047 2.085126 2.068460 2.553373 1.961233 ## [4,] 1.853065 2.102724 2.023489 2.201069 1.589020 1.762024 1.732880 ## [5,] 2.211788 1.835317 2.203315 2.130479 2.603895 2.352483 2.553764 ## [6,] 2.290308 1.676302 1.961986 2.136418 1.583103 1.976561 2.096849 ## y 8 y 9 y 10 ## [1,] 2.612733 1.871048 2.362851 ## [2,] 2.137262 2.312675 2.101397 ## [3,] 2.112843 1.932266 1.954944 ## [4,] 1.900633 1.997519 1.944015 ## [5,] 2.248523 2.326975 2.227459 ## [6,] 1.943711 1.461564 1.662695 #查看数据结构 str(y)

## num [1:2000, 1:10] 2.06 2.1 2.35 1.85 2.21 ... ## - attr(*, \ ## ..$ : NULL

## ..$ : chr [1:10] \ # 算法聚类

#聚类数为2,将数据聚成2个类别 cl=kmeans(y,2) #查看模型结果 summary(cl)

## Length Class Mode ## cluster 2000 -none- numeric ## centers 20 -none- numeric ## totss 1 -none- numeric ## withinss 2 -none- numeric

## tot.withinss 1 -none- numeric ## betweenss 1 -none- numeric ## size 2 -none- numeric ## iter 1 -none- numeric ## ifault 1 -none- numeric

#Length Class Mode

#cluster 2000 -none- numeric #centers 20 -none- numeric #totss 1 -none- numeric #withinss 2 -none- numeric #tot.withinss 1 -none- numeric #betweenss 1 -none- numeric #size 2 -none- numeric #iter 1 -none- numeric #ifault 1 -none- numeric pch1=rep(\,1000)#类标号 pch2=rep(\,1000) #数据可视化

par(mfrow=c(1,1))

plot(y,col=cl$cluster,pch=c(rep(\,1000),rep(\,1000)),main=\算法聚类图1\)#每个类样本

points(cl$centers,col=3,pch=\,cex=3)#每个类中心

## 算法聚类

# install.packages(\

library(\) pamcl=pam(y,2) #绘制聚类结果

par(mfrow=c(1,2))

plot(pamcl,main=\算法聚类图2\)

## 算法聚类

clarax=clara(y,2)

plot(clarax,main=\算法聚类图3\)

## 算法聚类

# install.packages(\ library(fpc)

## Warning: package 'fpc' was built under R version 3.3.3