【问题标题】:Rank features based on their frequency根据频率对特征进行排名
【发布时间】:2017-06-29 08:55:53
【问题描述】:

我有一个 0 和 1 的稀疏矩阵,它是训练数据 = numpy 2d 数组。

我只想保留前 K 个特征来描述我的数据。

我想根据频率计算前 K 个特征,即它们在整个矩阵的训练样本中出现的频率。

但是,我没有这些功能的确切名称。它们只是列。

如何计算它们的频率,最重要的是,如何选择矩阵中的前 K 个特征并删除其他特征?

【问题讨论】:

  • 每个特征都必须存在于每个数据样本中。这就是你将它提供给 scikit 的方式。你说的特征频率是什么意思。

标签: python numpy machine-learning scikit-learn feature-selection


【解决方案1】:

Scipy 稀疏矩阵可以 - 直到返回 matrix 而不是 array 对象的恼人倾向 - 在许多方面都可以像 arrays 一样使用,所以要提取特征频率并找到顶部,比如 4:

>>> features_present_in_sample = [[1,5], [0,3,7], [1,2], [0,4,6], [2,6]]
>>> features_per_sample=[len(s) for s in features_present_in_sample]
>>> features_flat = np.r_[tuple(features_present_in_sample)]
>>> boundaries = np.r_[0, np.add.accumulate(features_per_sample)]
>>> nsaamples = len(features_present_in_sample)
>>> nfeatures = np.max(features_flat) + 1
>>> data = sparse.csr_matrix((np.ones_like(features_flat), features_flat, boundaries), (nsaamples, nfeatures))
>>>
>>> data
<5x8 sparse matrix of type '<class 'numpy.int64'>'
        with 12 stored elements in Compressed Sparse Row format>
>>> data.todense()
matrix([[0, 1, 0, 0, 0, 1, 0, 0],
        [1, 0, 0, 1, 0, 0, 0, 1],
        [0, 1, 1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 1, 0, 1, 0],
        [0, 0, 1, 0, 0, 0, 1, 0]])
>>> frequencies = data.mean(axis=0)
>>> frequencies
matrix([[ 0.4,  0.4,  0.4,  0.2,  0.2,  0.2,  0.4,  0.2]])
>>> top4 = np.argpartition(-frequencies.A.ravel(), 4)[:4]
>>> top4
array([6, 0, 2, 1])

删除其他人:

>>> one_hot_top4 = np.zeros((nfeatures, 4), dtype=int)
>>> one_hot_top4[top4, np.arange(4)] = 1
>>> data @ one_hot_top4
array([[0, 0, 0, 1],
       [0, 1, 0, 0],
       [0, 0, 1, 1],
       [1, 1, 0, 0],
       [1, 0, 1, 0]], dtype=int64)

或(更好):

>>> one_hot_top4_sparse = sparse.csc_matrix((np.ones((4,), dtype=int), top4, np.arange(4+1)), (nfeatures, 4))
>>> data @ one_hot_top4_sparse
<5x4 sparse matrix of type '<class 'numpy.int64'>'
        with 8 stored elements in Compressed Sparse Row format>
>>> (data @ one_hot_top4_sparse).todense()
matrix([[0, 0, 0, 1],
        [0, 1, 0, 0],
        [0, 0, 1, 1],
        [1, 1, 0, 0],
        [1, 0, 1, 0]], dtype=int64)

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2019-06-10
    • 2014-02-11
    • 2014-02-12
    • 2020-08-26
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多