【问题标题】:Python K means clustering ArrayPython K 表示聚类数组
【发布时间】:2017-02-22 17:29:04
【问题描述】:

我正在寻找一种方法来使用 python 在 n 个集群中分割一个二维数组。我想使用 K 均值方法,但我没有找到任何代码。我尝试使用 sklearn 库的 k-means,但我不明白如何正确使用它。

【问题讨论】:

    标签: python arrays k-means


    【解决方案1】:

    来自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.]])
    

    【讨论】:

    • 是的,我已经尝试过了,但是使用 kmeans.labels_ 它只给我一个一维数组,我希望它给我和数组一样的输入数组,并且每个元素都更改为集群的数量它被分配到哪里
    【解决方案2】:

    一般来说,要使用 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

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 2016-09-06
      • 2012-12-09
      • 2016-10-25
      • 2021-02-06
      • 2013-03-14
      • 2017-10-15
      相关资源
      最近更新 更多