halcon 脚本代码实现简单的一维kmeans算法

kmeans(:: Props, K, Num : Classification)
N := |Props|-1

Seeds :=[]
for i := 0 to K-1 by 1
    tuple_rand(1,Rand)
    tuple_floor(Rand*N,seed)
    tuple_int(seed,seed)
    tuple_find(Seeds,seed, Indices)
    while(|Indices|>0 and Indices # -1)
        tuple_rand(1,Rand)
        tuple_floor(Rand*N,seed)
        tuple_find(Seeds,seed, Indices)
    endwhile
    Seeds :=[Seeds, seed]
    stop()
endfor

PSeeds :=Props[Seeds]

iterNum := 0
tuple_gen_const(N+1, -1, Classification)
tuple_max(Props,Max)
tuple_min(Props,Min)
delta := Max-Min
while(iterNum<Num)
    
    tuple_gen_const(N+1, -1, ClassificationNew)
    for j := 0 to N by 1
        Mini := delta
        for i := 0 to K-1 by 1            
           tuple_fabs(PSeeds[i] - Props[j],d)
           if(d<=Mini)
               ClassificationNew[j] := i
               Mini := d
           endif
*            stop()
        endfor
    endfor
    Classification := ClassificationNew
     tuple_equal(Classification,ClassificationNew,Equal)
    if(Equal = 1)
        break
    else
        Classification := ClassificationNew
        for i := 0 to K-1 by 1
            tuple_find(Classification,i,Indices1)
            tuple_mean(Props[Indices1],Mean)
            if(PSeeds[i] = Mean)
                continue
            else
                PSeeds[i] := Mean
            endif
        endfor
    endif
    iterNum := iterNum + 1 
endwhile
return ()

 以上代码简单实现了kmeans聚类算法,算法原理如下:

输入:样本数据集DD,聚类簇数k 
(1) 从样本中随机选取k个样本点作为初始的均值向量{μ1,μ2,⋯,μk}{μ1,μ2,⋯,μk} 
(2)循环以下几步直到达到停止条件: 
(2.1)令Ci=∅(1≤i≤k)Ci=∅(1≤i≤k) 
(2.2)对所有样本点计算他们到k个均值向量之间的距离,取其中距离最短的距离对应的均值向量的标记作为该点的簇标记,然后将该点加入相应的簇CiCi 
(2.3)对每一个簇计算他们新的均值向量μi=1|Ci|∑x∈Cixμi=1|Ci|∑x∈Cix,如果相比之前的向量有变化,就更新,将其作为新的均值向量,如果没有变化就不变

猜你喜欢

转载自blog.csdn.net/xiaoshuying/article/details/87709915