【问题标题】:Dealing with a large amount of unique words for text processing/tf-idf etc处理大量独特词进行文本处理/tf-idf 等
【发布时间】:2013-11-24 02:35:29
【问题描述】:

我正在使用 scikit 做一些文本处理,比如 tfidf。文件名的数量处理得很好(~40k)。但就唯一词的数量而言,我无法处理数组/矩阵,无论是获取打印的唯一词数量的大小,还是将 numpy 数组转储到文件中(使用 savetxt) .下面是回溯。如果我能获得 tfidf 的最高值,因为我不需要它们用于每个文档的每个单词。或者,我可以从计算中排除其他单词(不是停用词,而是我可以添加的文本文件中的一组单独的单词,这些单词将被排除)。不过,我不知道我会说的话是否会缓解这种情况。最后,如果我能以某种方式抓取矩阵的碎片,那也可以。任何处理这类事情的例子都会有所帮助,并给我一些想法的起点。 (PS 我查看并尝试了 Hashingvectorizer,但似乎我不能用它做 tfidf?)

Traceback (most recent call last):
  File "/sklearn.py", line 40, in <module>
    array = X.toarray()
  File "/home/kba/anaconda/lib/python2.7/site-packages/scipy/sparse/compressed.py", line 790, in toarray
    return self.tocoo(copy=False).toarray(order=order, out=out)
  File "/home/kba/anaconda/lib/python2.7/site-packages/scipy/sparse/coo.py", line 239, in toarray
    B = self._process_toarray_args(order, out)
  File "/home/kba/anaconda/lib/python2.7/site-packages/scipy/sparse/base.py", line 699, in _process_toarray_args
    return np.zeros(self.shape, dtype=self.dtype, order=order)
ValueError: array is too big.

相关代码:

path = "/home/files/"

fh = open('output.txt','w')


filenames = os.listdir(path)

filenames.sort()

try:
    filenames.remove('.DS_Store')
except ValueError:
    pass # or scream: thing not in some_list!
except AttributeError:
    pass # call security, some_list not quacking like a list!

vectorizer = CountVectorizer(input='filename', analyzer='word', strip_accents='unicode', stop_words='english') 
X=vectorizer.fit_transform(filenames)
fh.write(str(vectorizer.vocabulary_))

array = X.toarray()
print array.size
print array.shape

编辑:如果这有帮助,

print 'Array is:' + str(X.get_shape()[0])  + ' by ' + str(X.get_shape()[1]) + ' matrix.'

获取过大稀疏矩阵的维度,以我为例:

Array is: 39436 by 113214 matrix.

【问题讨论】:

    标签: numpy scipy scikit-learn tf-idf


    【解决方案1】:

    回溯在这里给出了答案:当您最后调用X.toarray() 时,它会将稀疏矩阵表示转换为密集表示。这意味着您现在不是为每个文档中的每个单词存储一个恒定数量的数据,而是为 all 个文档中的 all 个单词存储一个值。

    谢天谢地,大多数运算都使用稀疏矩阵,或者具有稀疏变体。只需避免致电 .toarray().todense() 即可。

    如需了解更多信息,请查看scipy sparse matrix documentation

    【讨论】:

    • 感谢您的回复。当我不使用 code.toarray()codecode.todense()code 时,我的所有代码都有效
    • 我可以使用哪些其他操作来访问结果或部分结果?我在链接中看到了对矩阵执行操作的示例。你能推荐一种切片方法吗?
    • 这取决于你想用矩阵做什么。如果您只是想四处逛逛,我建议您尝试使用较小的数据集并首先使用toarray() 查看它。一旦你知道你想做什么,你就可以找到稀疏函数来对大数据进行操作。
    • 我想做的一件事是,给定一个代表数组列的索引,我该如何提取这些索引?例如,我有 500 个,并且我想要所有行的该列索引的所有值。如果没有 .toarray() 我一直在寻找 link其他可能有效的解决方案.. 如果您有任何建议。
    • 接下来,对于 tfidf 矩阵,我想获得最高的 tfidf 值。我看到了如何为 tfidf 矢量化器设置最大特征量,但这是针对具有最高 tf 计数的单词。我仍然想获得 tfidf 的高值,其中可能包括低 tf 的单词。我查找的一个想法是执行类似 tf_idf_matrix.sum(axis=0) 之类的操作,它将汇总列。这在我的代码中有效,但由于有 113k 列,打印不会全部显示。如果我可以使用 argsort 之类的方法来访问前 K 列的总和值,那将很有帮助。
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 2019-04-27
    • 2017-03-14
    • 1970-01-01
    • 2021-04-08
    • 2017-05-08
    • 2012-10-27
    • 1970-01-01
    相关资源
    最近更新 更多