聚类(R)

来源:互联网 发布:php商城系统 开源 编辑:程序博客网 时间:2024/06/08 09:45
####聚类######随机产生三个簇点c1<-cbind(rnorm(100,2,1),rnorm(100,2,2))c2<-cbind(rnorm(80,3,1),rnorm(80,20,1))c3<-cbind(rnorm(60,15,1),rnorm(60,25,1))v=rbind(c1,c2,c3)vplot(v)cl=kmeans(v,3)clcl$itercl$withinssplot(v, col = cl$cluster)cbind(v,cl$cluster)points(cl$centers, col = 1:2, pch = 8, cex = 2)data(USArrests)USArrestsplot(USArrests)cl = kmeans(scale(USArrests),4)cldist(v)plot(hclust(dist(v),method = 'single'))plot(hclust(dist(v),method = 'single'),hang = -1)hc<-plot(hclust(dist(v),method = 'ward.D2'))cutree(hc,k=3)attach(iris) #为了使用数据集的名称names(iris)Speciesiris1=iris[,-5]iris1k = 1:15ss = NULLfor(i in 1:15){  ss[i] = kmeans(scale(iris1),i)$tot.withnss/(kmeans(scale(iris1),i)$totss)}plot(ss,k,type = 'l')hc1 <- hclust(dist(cent)^2, method = "cen", members = table(memb))opar <- par(mfrow = c(1, 2))plot(hc,  labels = FALSE, hang = -1, main = "Original Tree")plot(hc1, labels = FALSE, hang = -1, main = "Re-start from 3 clusters")par(opar)   #2. 练习:随机生成三个簇点:c1<-cbind(rnorm(30,2,1),rnorm(30,2,1))c2<-cbind(rnorm(30,3,1),rnorm(30,20,1))c3<-cbind(rnorm(30,15,1),rnorm(30,25,1))v1=cbind(c1,c2,c3)#####3. 数据集用的是iris#第一步:对数据集进行初步统计分析#检查数据的维度dim(iris)#显示数据集中的列名names(iris)#显示数据集的内部结构str(iris)#显示数据集的属性attributes(iris)#$names –就是数据集的列名#$row.names –每行数据的标号#$class –表示类别#查看数据集的前五项数据情况iris[1:5,]#查看数据集中属性Sepal.Length前10行数据iris[1:10, "Sepal.Length"]#同上iris$Sepal.Length[1:10]#显示数据集中每个变量的分布情况summary(iris)#####显示iris数据集列Species中各个值出现频次table(iris$Species)#根据列Species画出饼图pie(table(iris$Species))#算出列Sepal.Length的所有值的方差var(iris$Sepal.Length)#算出列iris$Sepal.Length和iris$Petal.Length的协方差cov(iris$Sepal.Length, iris$Petal.Length)#算出列iris$Sepal.Length和iris$Petal.Length的相关系数, 从结果看这两个值是强相关。cor(iris$Sepal.Length, iris$Petal.Length)#画出列iris$Sepal.Length分布柱状图hist(iris$Sepal.Length)#画出列iris$Sepal.Length的密度函数图plot(density(iris$Sepal.Length))#画出列iris$Sepal.Length和iris$Sepal.Width的散点图plot(iris$Sepal.Length, iris$Sepal.Width)#绘出矩阵各列的散布图plot(iris)#ORpairs(iris)#第二步:进行Kmean聚类分析
原创粉丝点击