参考

kmeans clustering

Data Clustering: K-means and Hierarchical Clustering

kmeans 函数

kc <- kmeans(x,  #数据
centers,   #类别个数(中心个数)
iter.max = 10, #迭代次数
nstart = 1,  #随机集合数
algorithm = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen"), #算法,其中 Lloyd = Forgy
trace=FALSE  #是否给出更多消息
)

#函数运算后返回对象kc,其中有多项值
#cluster: 分类结果数组,第i个值表示第i行数据所属分类
#centers: kmeans聚类的中心坐标
#totss: 总距离平方和
#withinss: 各个聚类内部 距离平方和 的数组
#tot.withinss: sum(withinss) 聚类内部平方和 之和
#betweenss: 跨聚类 距离平方和之和
#size: 各个聚类包含的节点个数
#iter: 迭代次数
#ifault: 可能存在的问题标识

示例代码

#kmeans
#options(echo=TRUE) 

args <- commandArgs(trailingOnly = TRUE)
print(args)
dfile <- args[1]
clnum <- args[2]
alg <- args[3]

d <- read.table(dfile,header=TRUE,sep=',')
somekey <- d$somekey
d$somekey <- NULL

(kc <- kmeans(d, clnum, algorithm = alg))
d$somekey <- somekey
d$kmeans <- kc$cluster
write.table(d, file=paste(dfile,'cluster',clnum,'algorithm',alg,'out.csv',sep='.'), quote=FALSE, row.names=FALSE, sep=',')
save(kc, file=paste(dfile,'cluster',clnum,'algorithm',alg,'kmeans.RData',sep='.'))

#kc$size
#which(d$kmeans!=2)
#d[d$kmeans!=2,]


Published

22 September 2014

Tags


Share On