【问题标题】:Randomly sample x% of each cluster随机抽样每个集群的 x%
【发布时间】:2017-03-13 03:56:37
【问题描述】:

我正在开展一个项目,旨在利用我的数据集的集群结构来改进用于 binray 分类的监督主动学习分类器。我使用以下代码对我的数据进行聚类,X 使用 scikit-leanr 的 K-Means 实现:

k = KMeans(n_clusters=(i+2), precompute_distances=True, ).fit(X)
df = pd.DataFrame({'cluster' : k.labels_, 'percentage posotive' : y})
a = df.groupby('cluster').apply(lambda cluster:cluster.sum()/cluster.count())

这两个类是正数(用 1 表示)和负数(用 0 表示),并存储在数组y 中。 此代码首先对X 进行聚类,然后将每个聚类数和其中的阳性实例的百分比存储在一个数据框中。

我现在想从每个集群中随机选择点,直到我采样了 15%。我该怎么做?

这里要求的是一个包含测试数据集的简化脚本:

from sklearn.cluster import KMeans
import pandas as pd
X = [[1,2], [2,5], [1,2], [3,3], [1,2], [7,3], [1,1], [2,19], [1,11], [54,3], [78,2], [74,36]]
y = [0,0,0,0,0,0,0,0,0,1,0,0]
k = KMeans(n_clusters=(4), precompute_distances=True, ).fit(X)
df = pd.DataFrame({'cluster' : k.labels_, 'percentage posotive' : y})
a = df.groupby('cluster').apply(lambda cluster:cluster.sum()/cluster.count())
print(a)

注意:真正的数据集要大得多,包含数千个特征和数千个数据实例。

回复@SandipanDey

我不能告诉你太多,但基本上我们正在处理一个高度不平衡的数据集 (1:10,000),我们只对识别召回率 > 95% 的少数类示例感兴趣,同时减少请求的标签数量. (召回需要如此之高,因为它与医疗保健相关。)

少数样本聚集在一起,任何包含正实例的集群通常至少包含 x%,因此通过抽样 x%,我们确保我们识别出具有任何正实例的所有集群。因此,我们能够快速减少具有潜在积极意义的数据集的大小。然后可以将该部分数据集用于主动学习。我们的方法大致受到'Hierarchical Sampling for Active Learning'

的启发

【问题讨论】:

  • 我不认为你用 1 也代表否定。无论如何,您发布一个(小)示例数据集来执行此操作?
  • @Denziloe 很好,已进行相应编辑。即将添加小型测试数据集。
  • @Denziloe 已添加测试数据集。
  • 非常感谢@scutnex 添加描述。

标签: python scikit-learn


【解决方案1】:

如果我理解正确,下面的代码应该可以达到目的:

import numpy as np

# For each cluster 
# (1) Find all the points from X that are assigned to the cluster. 
# (2) Choose x% from those points randomly.

n_clusters = 4
x = 0.15 # percentage

for i in range(n_clusters):

    # (1) indices of all the points from X that belong to cluster i
    C_i = np.where(k.labels_ == i)[0].tolist() 
    n_i = len(C_i) # number of points in cluster i

    # (2) indices of the points from X to be sampled from cluster i
    sample_i = np.random.choice(C_i, int(x * n_i)) 
    print i, sample_i

出于好奇,你打算如何使用这些x% 积分进行主动学习?

【讨论】:

  • 谢谢!提供了方法的简要说明
  • 非常感谢@scutnex 添加描述,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多