0

我有一个0s和1s的稀疏矩阵,它是训练数据= numpy二维数组。基于它们的频率的排名特征

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

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

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

我该如何计算他们的频率,最重要的是,我该如何选择矩阵中的顶级K特征并删除其他特征?

+0

每个数据样本中必须包含每个特征。这就是你如何将它提供给scikit。你的意思是什么特征的频率。 –

回答

0

SciPy的稀疏矩阵可以 - 到他们讨厌的倾向返回matrixarray对象 - 在许多方面就像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)