scikit-learn kmeans clustering

时间:2016-07-13 14:54:33

标签: python scikit-learn cluster-analysis k-means

如果我已经有一个可以作为初始质心的numpy数组,我该如何正确初始化kmeans算法?我正在使用scikit-learn Kmeans类

这篇文章(k-means with selected initial centers)表示如果我使用numpy数组作为初始质心,我只需要设置n_init = 1,但我不确定我的初始化是否正常工作

Naftali Harris的优秀可视化页面显示了我想要做的事情 http://www.naftaliharris.com/blog/visualizing-k-means-clustering/

“我会选择” - > “Packed Circles” - >跑kmeans

#numpy array of initial centroids
startpts=np.array([[-0.12, 0.939, 0.321, 0.011], [0.0, 0.874, -0.486, 0.862], [0.0, 1.0, 0.0, 0.033], [0.12, 0.939, 0.321, -0.7], [0.0, 1.0, 0.0, -0.203], [0.12, 0.939, -0.321, 0.25], [0.0, 0.874, 0.486, -0.575], [-0.12, 0.939, -0.321, 0.961]], np.float64)

centroids= sk.KMeans(n_clusters=8, init=startpts, n_init=1)

centroids.fit(actual_data_points)

#get the array
centroids_array=centroids.cluster_centers_

1 个答案:

答案 0 :(得分:6)

是的,通过init设置初始质心应该有效。以下是来自scikit-learn documentation的引用:

 init : {‘k-means++’, ‘random’ or an ndarray}

     Method for initialization, defaults to ‘k-means++’:   

     If an ndarray is passed, it should be of shape (n_clusters, n_features)
     and gives the initial centers.
  

(n_clusters, n_features)指的是什么形状?

形状要求意味着init必须具有完全n_clusters行,并且每行中的元素数量应与actual_data_points的维度相匹配:

>>> init = np.array([[-0.12, 0.939, 0.321, 0.011],
                     [0.0, 0.874, -0.486, 0.862],
                     [0.0, 1.0, 0.0, 0.033],
                     [0.12, 0.939, 0.321, -0.7],
                     [0.0, 1.0, 0.0, -0.203],
                     [0.12, 0.939, -0.321, 0.25],
                     [0.0, 0.874, 0.486, -0.575],
                     [-0.12, 0.939, -0.321, 0.961]],
                    np.float64)
>>> init.shape[0] == 8  
True  # n_clusters
>>> init.shape[1] == actual_data_points.shape[1]
True  # n_features
  

什么是n_features?

n_features是您样本的维度。例如,如果您要在2D平面上聚类点,n_features将为2。