KMeans++ 的初始化方法:
1、隨機選一個樣本作爲第一個簇中心。
2、計算每個樣本到最近簇中心的距離。
3、以距離爲概率隨機選擇下一個簇中心。
4、重複步驟2和3,直到找到K個簇中心。
vlfeat \ kmeans.c \ _vl_kmeans_init_centers_plus_plus_ 中的代碼片段如下:
x = vl_rand_uindex (rand, numData) ;
c = 0 ;
while (1) {
TYPE energy = 0 ;
TYPE acc = 0 ;
TYPE thresh = (TYPE) vl_rand_real1 (rand) ;
//把隨機選的樣本作爲簇中心。
memcpy ((TYPE*)self->centers + c * dimension,
data + x * dimension,
sizeof(TYPE) * dimension) ;
c ++ ;
if (c == numCenters) break ;
//計算所有樣本到當前簇中心的距離。
VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)
(distances,
dimension,
(TYPE*)self->centers + (c - 1) * dimension, 1,
data, numData,
distFn) ;
//計算所有樣本到最近簇中心的距離,並求和。
for (x = 0 ; x < numData ; ++x) {
minDistances[x] = VL_MIN(minDistances[x], distances[x]) ;
energy += minDistances[x] ;
}
//隨機數落在距離和中的哪一段,就以對應樣本爲下一個簇中心。
for (x = 0 ; x < numData - 1 ; ++x) {
acc += minDistances[x] ;
if (acc >= thresh * energy) break ;
}
}