K cluster number

2019-10-13  本文已影响0人  Latupa_天空之城
1. 生成模拟数据集
#install.packages("MixSim")
#install.packages("MASS")
library(MixSim)
# 生成5个中心点,8维属性的数据模型 
data = MixSim(MaxOmega=0,  K=5,  p=8,  ecc=0.5,  int=c(10, 100))
# 根据模型获得1000次观察的数据集
A <- simdataset(n=1000,  Pi=data$Pi, Mu=data$Mu, S=data$S, n.out=0)
data <- A$X
# 数据标准化
data <- t(apply(data, 1, scale))
# 定义行列名字
rownames(data) <- paste("Gene", 1:1000, sep="_")
colnames(data) <- letters[1:8]
head(data)
2. K-means聚类

2.1 需要确定聚出的类的数目。可通过遍历多个不同的聚类数计算其类内平方和的变化,并绘制线图,一般选择类内平方和降低开始趋于平缓的聚类数作为较优聚类数, 又称elbow算法。

tested_cluster <- 12
wss <- (nrow(data)-1) * sum(apply(data, 2, var)) #data为要处理的数据
for (i in 2:tested_cluster) {
    wss[i] <- kmeans(data, centers=i,iter.max=100,  nstart=25)$tot.withinss
}
plot(1:tested_cluster, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares")

2.2 K-means聚类起始点为随机选取,容易获得局部最优,需重复计算多次,选择最优结果。

#install.packages("fpc")
library(cluster)
library(fpc)
# iter.max: 最大迭代次数
# nstart: 选择的随机集的数目
# centers: 上一步推测出的最优类数目
center = 5
fit <- kmeans(data, centers=center, iter.max=100, nstart=25)
withinss <- fit$tot.withinss
print(paste("Get withinss for the first run", withinss))
try_count = 10
for (i in 1:try_count) {
  tmpfit <- kmeans(data, centers=center, iter.max=100, nstart=25)
  tmpwithinss <- tmpfit$tot.withinss
  print(paste(("The additional "), i, 'run, withinss', tmpwithinss))
  if (tmpwithinss < withinss){
    withins <- tmpwithinss
    fit <- tmpfit
  }
}

fit_cluster = fit$cluster
clusplot(data, fit_cluster, shade=T, labels=5, lines=0, color=T,lty=4, main='K-means clusters') #此步有问题
3. K-medoids聚类

3.1 不同的分类书计算出的silhouette值如下,越趋近于1说明分出的类越好。

fit_pam <- pamk(data, krange=2:10, critout=T)
fit_pam$nc #获取分类的数目
layout(matrix(c(1, 2), 1, 2)) 
plot(fit_pam$pamobject)
layout(matrix(1)) #改回每页一张图
fit_cluster <- fit_pam$pamobject$clustering #获取分类信息

参考网址:
https://blog.csdn.net/qazplm12_3/article/details/78904744

上一篇 下一篇

猜你喜欢

热点阅读