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)