【发布时间】:2017-02-22 17:29:04
【问题描述】:
我正在寻找一种方法来使用 python 在 n 个集群中分割一个二维数组。我想使用 K 均值方法,但我没有找到任何代码。我尝试使用 sklearn 库的 k-means,但我不明白如何正确使用它。
【问题讨论】:
我正在寻找一种方法来使用 python 在 n 个集群中分割一个二维数组。我想使用 K 均值方法,但我没有找到任何代码。我尝试使用 sklearn 库的 k-means,但我不明白如何正确使用它。
【问题讨论】:
来自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.]])
【讨论】:
一般来说,要使用 sklearn 中的模型,您必须:
导入:from sklearn.cluster import KMeans
以所选参数kmeans = KMeans(n_clusters=2) 为例,初始化表示模型的对象。
使用您的数据训练它,使用.fit() 方法:kmeans.fit(points)。现在对象kmeans 的属性中包含与您的训练模型相关的所有数据。例如,kmeans.labels_ 对应一个数组,其中包含用于训练模型的每个点的标签。
.predict(new_points) 方法获取离点或点数组最近的簇的标签。您可以从 kmeansalgorithm 页面获取所有属性: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
【讨论】: