2017-02-22 153 views
0

我正在尋找一種方法來分割與python n個羣集中的二維數組。我想使用K平均法,但我沒有找到任何代碼。我嘗試了sklearn庫的k-means,但我還沒有理解如何正確使用它。蟒蛇K意味着羣集陣列

回答

0

通常,使用一個模型從sklearn你必須:

  1. 進口它:from sklearn.cluster import KMeans

  2. 初始化表示與所述選擇的參數,kmeans = KMeans(n_clusters=2)模型中的對象,作爲一個例子。

  3. 用您的數據訓練,使用.fit()方法:kmeans.fit(points)。現在對象kmeans在其屬性中包含與您的訓練模型相關的所有數據。作爲示例,kmeans.labels_對應於具有用於訓練模型的每個點的標籤的陣列。

  4. 使用.predict(new_points)方法將最近羣集的標籤獲取到一個點或一組點。

你可以得到一切從kmeansalgorithm頁面的屬性: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html

0

http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans

from sklearn.cluster import KMeans 
import numpy as np 

#this is your array with the values 
X = np.array([[1, 2], [1, 4], [1, 0], 
       [4, 2], [4, 4], [4, 0]]) 


#This function creates the classifier 
#n_clusters is the number of clusters you want to use to classify your data 
kmeans = KMeans(n_clusters=2, random_state=0).fit(X) 

#you can see the labels with: 
print kmeans.labels_ 

# the output will be something like: 
#array([0, 0, 0, 1, 1, 1], dtype=int32) 
# the values (0,1) tell you to what cluster does every of your data points correspond to 

#You can predict new points with 
kmeans.predict([[0, 0], [4, 4]]) 

#array([0, 1], dtype=int32) 

#or see were the centres of your clusters are 
kmeans.cluster_centers_ 
#array([[ 1., 2.], 
#  [ 4., 2.]]) 
+0

是的,我已經tryed它,但它kmeans.labels_給我只能一維數組,我希望它給我和數組像輸入數組和每個元素更改爲它被分配的集羣的數量 –