baibx8612 2016-10-08 12:51
浏览 789

最近在学聚类分析 在网上发现一个用R写的聚类算法 但是自己怎么也调不通 求大牛帮个忙

结果显示迭代没问题,但是簇间距离是0那应该就是把所有的数据都算作一类了
My_kmeans<-function(data,k,max.iter=10){

rows<-nrow(data)
cols<-ncol(data)

within<-matrix(0,nrow=k,ncol=1)
between<-0
iter=0

indexMatrix<-matrix(0,nrow=rows,ncol=2)

centers<-matrix(0,nrow=k,ncol=cols)
randSeveralInteger<-as.vector(sample(1:rows,size=k))
for(i in 1:k){
indexMatrix[randSeveralInteger[i],1]<-i
centers[i,]<-data[randSeveralInteger[i],]
centers<-matrix(centers,k,cols)
}
changed=TRUE #changed

while(changed){

if(iter>=max.iter)
  break

changed=FALSE


for(i in 1:rows){ 
  initialDistance<-10000 
  previousCluster<-indexMatrix[i,1]
  for(j in 1:k){ 
    currentDistance<-(sum((data[i,]-centers[j,])^2))^0.5
    if(currentDistance<=initialDistance)
       initialDistance<-currentDistance 
       indexMatrix[i,1]<-j 
       indexMatrix[i,2]<-currentDistance  
  } 
}


if(previousCluster!=indexMatrix[i,1]) 
  changed=TRUE

}

for(m in 1:k){
clusterMatrix<-data[indexMatrix[,1]==m,]
clusterMatrix<-as.matrix(clusterMatrix)
if(nrow(clusterMatrix)>0){
centers[m,]<-colMeans(clusterMatrix)
}
else{
centers[m,]<-centers[m,]
}

iter=(iter+1)
}

ss<-function(x) sum(scale(x,scale=FALSE)^2)
between<-ss(centers[indexMatrix[,1],])
within<-sapply(split(as.data.frame(data),indexMatrix[,1]),ss)
twithin<-sum(within) #total within-clustersum of squares

result<-list(cluster=indexMatrix[,1],tot.withinss=twithin,betweenss=between,iteration=iter)

return(result)
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥200 uniapp长期运行卡死问题解决
    • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
    • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
    • ¥15 乘性高斯噪声在深度学习网络中的应用
    • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决