1.
下面给出五个元素两两之间的距离,试利用最短距离法、最长距离法和类平均法做出五个元素的谱系聚类,画谱系图并做出比较。
read7.1,comment1 2 3
| d = matrix(data=c(0,0,0,0,0,4,0,0,0,0,6,9,0,0,0,1,7,10,0,0,6,3,5,8,0),nrow=5,ncol=5,byrow = TRUE);d x = scale(d) # 数据标准化 D = dist(x);D # 默认为 Euclidean 距离
|
1 2 3 4
| # 最短距离法 hc1 = hclust(D, method='single') data.frame(hc1$merge,hc1$height) plot(hc1)
|
1 2 3 4
| # 最长距离法 hc2=hclust(D,"complete");hc2 data.frame(hc2$merge,hc2$height) plot(hc2)
|
1 2 3 4
| # 类平均法 hc3=hclust(D,"average");hc3 data.frame(hc3$merge,hc3$height) plot(hc3)
|
总结:根据以上作图分析可知使用最短距离法效果相对较好
2.
为了比较我国31个省、市、自治区2013年和2007年城镇居民生活消费的分布规律,根据调查资料做区域消费类型划分,并将2013年和2007年的数据进行对比分析。今收集了八个反映城镇居民生活消费结构的指标(2013年数据): 试对该数据进行聚类分析。
read7.2,comment1 2
| library(openxlsx) d7.2 = read.xlsx("../Res/mvexer5.xlsx", "E7.2", rowNames=T);head(d7.2)
|
1 2 3
| Z = scale(d7.2);Z # 数据标准化 boxplot(Z) # 箱型图 D = dist(Z)
|
block7.2.1,comment1 2 3 4
| hc = hclust(D, 'single') # 最短距离法 plot(hc);rect.hclust(hc, 2);cutree(hc, 2) # 分2类 plot(hc);rect.hclust(hc, 3);cutree(hc, 3) # 分3类 plot(hc);rect.hclust(hc, 4);cutree(hc, 4) # 分4类
|
1 2 3 4
| hc2 = hclust(D, 'ward.D2') # Ward.D2 法 plot(hc2);rect.hclust(hc2, 2);cutree(hc2, 2) # 分2类 plot(hc2);rect.hclust(hc2, 3);cutree(hc2, 3) # 分3类 plot(hc2);rect.hclust(hc2, 4);cutree(hc2, 4) # 分4类
|
1 2
| # kmeans 聚类法 kmeans(Z, 2)$cluster # 分2类
|
1
| kmeans(Z, 3)$cluster # 分3类
|
1
| kmeans(Z, 4)$cluster # 分4类
|
总结以上的分析结果,使用ward.D2方法的效果较好,且分为四类较为合适。
3.
按例7-3模拟方法对\(n=20,50,100,1000,10000\)分别进行kmeans法聚类分析。
为了重复模拟,可以将例7-3的方法编成函数:
block7.3.1}1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| kMock<-function(n, svar=0.3) { set.seed(123) # 设定种子数 x1 = matrix(rnorm(n*10, 0, svar), ncol = 10) # 均值为 0, 标准差为 svar 的 n*10 正态随机矩阵 x2 = matrix(rnorm(n*10, 1, svar), ncol = 10) # 均值为 1, 标准差为 svar 的 n*10 正态随机矩阵 X = rbind(x1, x2) # 形成 随机矩阵 H = hclust(dist(X)) plot(H);rect.hclust(H,2); cutree(H, 2) # 系统聚类结果 km = kmeans(X, 2) # K-means 聚类 #table(km) kc = km$cluster # 分类结果 #plot(X, pch = kc) plot(X, pch = kc, col = kc) }
|
再将n=20,50,100,1000,10000分别带入:
block7.3.2,comment