从sklearn CountVectorizer稀疏矩阵中仅筛选特定单词

3

我有一个充满文本的pandas系列。使用sklearn包中的CountVectorizer函数,我已经计算出了稀疏矩阵。我已经识别出了前几个单词。现在我想仅针对这些顶部单词过滤我的稀疏矩阵。

原始数据包含超过7000行,并且包含超过75000个单词。因此,我在这里创建了一个样本数据。

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
words = pd.Series(['This is first row of the text column',
                   'This is second row of the text column',
                   'This is third row of the text column',
                   'This is fourth row of the text column',
                   'This is fifth row of the text column'])
count_vec = CountVectorizer(stop_words='english')
sparse_matrix = count_vec.fit_transform(words)

我已经为该列中的所有单词创建了稀疏矩阵。在这里,只是为了打印我的稀疏矩阵,我使用 .toarray() 函数将其转换为数组。

print count_vec.get_feature_names()
print sparse_matrix.toarray()
[u'column', u'fifth', u'fourth', u'row', u'second', u'text']
[[1 0 0 1 0 1]
 [1 0 0 1 1 1]
 [1 0 0 1 0 1]
 [1 0 1 1 0 1]
 [1 1 0 1 0 1]]

现在我正在使用以下方法查找经常出现的单词。
# Get frequency count of all features
features_count = sparse_matrix.sum(axis=0).tolist()[0]
features_names = count_vec.get_feature_names()
features = pd.DataFrame(zip(features_names, features_count), 
                                columns=['features', 'count']
                               ).sort_values(by=['count'], ascending=False)

  features  count
0   column      5
3      row      5
5     text      5
1    fifth      1
2   fourth      1
4   second      1

从上面的结果可以看出,经常出现的单词是columnrowtext。 现在我想仅针对这些单词过滤我的稀疏矩阵。 我不想将稀疏矩阵转换为数组然后再进行过滤,因为我的原始数据中有很多单词,会导致内存错误。
我能够获得稀疏矩阵的唯一方法是再次使用vocabulary属性重复这些特定单词的步骤,如下所示。
countvec_subset = CountVectorizer(vocabulary= ['column', 'text', 'row'])

我希望你能够提供更好的解决方案,让我可以直接针对这些单词过滤稀疏矩阵,而不是需要重新创建一个新的矩阵。

1个回答

5

您可以使用切片处理稀疏矩阵。需要派生出用于切片的列。 sparse_matrix [:,columns]

In [56]: feature_count = sparse_matrix.sum(axis=0)

In [57]: columns = tuple(np.where(feature_count == feature_count.max())[1])

In [58]: columns
Out[58]: (0, 3, 5)

In [59]: sparse_matrix[:, columns].toarray()
Out[59]:
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]], dtype=int64)

In [60]: type(sparse_matrix[:, columns])
Out[60]: scipy.sparse.csr.csr_matrix

In [71]: np.array(features_names)[list(columns)]
Out[71]:
array([u'column', u'row', u'text'],
      dtype='<U6')

被切片的子集仍然是一个scipy.sparse.csr.csr_matrix

有没有想法如何根据计数选择前n个单词? - Kathirmani Sukumar
np.array(feature_count)[0].argsort()[-4:][::-1] 应该会给你前四个。可能还有更好的方法。 - Zero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接