R语言K-mean自编函数实现半成品
作者:互联网
一个不知道哪里出错了的自编函数
小惠作业
My_kmeans <- function(data,k,max.iter=10){
iter = 0
recordMatrix <- matrix(0,nrow=norm(data),ncol=2)
centers <- matrix(0,nrow=k,ncol=ncol(data))
cl=ncol(centers)
#初始点随机设置
for (j in 1:k) {
for (i in 1:cl) {
centers[j,i]=data[sample(1:nrow(data)),1][sample(1:ncol(data),1)]}
}
#循环
loop=TRUE
while(loop){
if(iter>max.iter)
break
loop=FALSE
for (i in 1:norm(data)) {
previous=recordMatrix[i,1]
ordis=1000000
#分组
for (j in 1:k) {
distance<-as.numeric((data[i,]-centers[j,])%*%t((data[i,]-centers[j,])))
distance<-sqrt(distance)
if(distance<ordis){
ordis<-distance
recordMatrix[i,1]=j
recordMatrix[i,2]=distance}}
#如果分组一有变化就继续循环
if(recordMatrix[i,1]!=previous){
loop=TRUE
}
#修改center矩阵
for(m in 1:k){
clusterMatrix <- data[recordMatrix[,1]==m,]
clusterMatrix <- as.matrix(clusterMatrix)
if(nrow(clusterMatrix)>0){
centers[m,] <- colMeans(clusterMatrix)
}
else{
centers[m,] <- centers[m,]
}
}
iter=iter+1
}}}
标签:distance,半成品,自编,iter,recordMatrix,data,centers,loop,mean 来源: https://blog.csdn.net/weixin_43207304/article/details/89284656