【发布时间】:2019-03-29 01:38:05
【问题描述】:
我正在使用 TFIDF 稀疏矩阵进行文档分类,并且希望仅保留每个文档的前 n 个(例如 50 个)术语(按 TFIDF 分数排名)。请参阅下面的编辑。
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
tfidfvectorizer = TfidfVectorizer(analyzer='word', stop_words='english',
token_pattern='[A-Za-z][\w\-]*', max_df=0.25)
n = 50
df = pd.read_pickle('my_df.pickle')
df_t = tfidfvectorizer.fit_transform(df['text'])
df_t
Out[15]:
<21175x201380 sparse matrix of type '<class 'numpy.float64'>'
with 6055621 stored elements in Compressed Sparse Row format>
我已经尝试按照this post中的示例进行操作,虽然我的目的不是显示特征,而只是在训练之前为每个文档选择前n个。但是我得到一个内存错误,因为我的数据太大而无法转换为密集矩阵。
df_t_sorted = np.argsort(df_t.toarray()).flatten()[::1][n]
Traceback (most recent call last):
File "<ipython-input-16-e0a74c393ca5>", line 1, in <module>
df_t_sorted = np.argsort(df_t.toarray()).flatten()[::1][n]
File "C:\Users\Me\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 943, in toarray
out = self._process_toarray_args(order, out)
File "C:\Users\Me\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\sparse\base.py", line 1130, in _process_toarray_args
return np.zeros(self.shape, dtype=self.dtype, order=order)
MemoryError
有没有什么方法可以在不使用密集表示(即不使用 toarray() 调用)并且不减少比我已经拥有的特征空间更多的情况下(使用 min_df)来做我想做的事情?
注意:max_features 参数不是我想要的,因为它只考虑“按词频在整个语料库中排序的最高 max_features”(文档here),而我想要的是文档级别的排名。
编辑:我想知道解决这个问题的最佳方法是否是将所有特征的值除了 n-best 设置为零。我这样说是因为已经计算了词汇表,所以特征索引必须保持不变,因为我想将它们用于其他目的(例如,可视化对应于 n-best 的实际单词功能)。
一位同事编写了一些代码来检索 n 个排名最高的特征的索引:
n = 2
tops = np.zeros((df_t.shape[0], n), dtype=int) # store the top indices in a new array
for ind in range(df_t.shape[0]):
tops[ind,] = np.argsort(-df_t[ind].toarray())[0, 0:n] # for each row (i.e. document) sort the (inversed, as argsort is ascending) list and slice top n
但从那里,我需要:
- 检索剩余(即排名最低的)索引列表并“就地”修改值,或
- 遍历原始矩阵 (
df_t) 并将所有值设置为 0,tops中的 n 个最佳索引除外。
有一个帖子 here 解释如何使用 csr_matrix,但我不确定如何将其付诸实践以获得我想要的。
【问题讨论】:
标签: python scikit-learn sparse-matrix text-classification tf-idf