【问题标题】:Effectively select data points that are near to the center of the cluster有效选择靠近集群中心的数据点
【发布时间】:2018-12-05 03:36:02
【问题描述】:

假设我有一个这样的数据集:

import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline

X,y = make_blobs(random_state=101) # My data

palette = sns.color_palette('bright',3)
sns.scatterplot(X[:,0], X[:,1],palette=palette,hue=y) # Visualizing the data

我想选择靠近集群中心的数据。说,我想从cluster '0'中选择靠近中心的数据,我目前是这样做的:

label_0 = X[y==0] # Want to select data from the label '0'

data_index = 2 # Manaully pick the point
sns.scatterplot(X[:,0], X[:,1],palette=palette,hue=y)
plt.scatter(label_0[data_index][0],label_0[data_index][1],marker='*')

由于离中心不近,我换了索引,再选一个。

data_index = 4
sns.scatterplot(X[:,0], X[:,1],palette=palette,hue=y)
plt.scatter(label_0[data_index][0],label_0[data_index][1],marker='*')

现在很接近了。但我想知道是否有更有效的方法来实现这一目标?像这样的小数据集是可以管理的,但是如果我的数据集有数千个点,我认为这种方法不再适用。

【问题讨论】:

    标签: python-3.x seaborn data-science


    【解决方案1】:

    一种方法是使用K-means algorithm。 这将帮助您找到每个集群的中心。

    鉴于您的数据集,步骤如下:

    1) 求聚类数

    num_clusters=len(np.unique(y)) #here 3
    

    2) 将scikit's k-means clustering 应用于您的数据

    from sklearn.cluster import KMeans
    kmeans = KMeans(n_clusters=num_clusters, random_state=0).fit(X)
    

    3) 找到每个簇的中心

    centers=kmeans.cluster_centers_ # gives the centers of each cluster
    # array([[ 0.26542862,  1.85466779],
    #        [-9.50316411, -6.52747391],
    #        [ 3.64354311,  6.62683956]])
    

    4) 由于这些中心可能不属于您的原始数据,我们需要找到离它们最近的点

    from scipy import spatial
    
    def nearest_point(array,query):
        return array[spatial.KDTree(array).query(query)[1]]
    
    nearest_centers=np.array([nearest_point(X,center) for center in centers])
    # array([[ 0.19313183,  1.80387958],
    #       [-9.12488396, -6.32638926],
    #       [ 3.65986315,  6.69035824]])
    

    5) 绘制原始数据和中心

    sns.scatterplot(X[:,0], X[:,1],palette=palette,hue=y) 
    for nc in nearest_centers:
        plt.scatter(nc[0],nc[1],marker='*',color='r')
    

    中心用红叉表示:

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 2019-08-25
      • 2021-10-16
      相关资源
      最近更新 更多