【发布时间】:2017-06-22 19:37:54
【问题描述】:
我有一个由 W 稀疏矩阵 word_freqs 存储在 D 中的语料库的词袋表示。每一行是一个文档,每一列是一个单词。给定元素word_freqs[d,w] 表示文档d 中单词w 的出现次数。
我正在尝试通过 W 矩阵 not_word_occs 获得另一个 D,其中,对于 word_freqs 的每个元素:
- 如果
word_freqs[d,w]为零,则not_word_occs[d,w]应为一。 - 否则,
not_word_occs[d,w]应为零。
最终,这个矩阵需要与其他可能密集或稀疏的矩阵相乘。
我尝试了很多方法,包括:
not_word_occs = (word_freqs == 0).astype(int)
这个词是玩具示例,但我的实际数据(大约为 18,000x16,000)导致 MemoryError。
我也试过np.logical_not():
word_occs = sklearn.preprocessing.binarize(word_freqs)
not_word_occs = np.logical_not(word_freqs).astype(int)
这看起来很有希望,但 np.logical_not() 不适用于稀疏矩阵,并出现以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
任何想法或指导将不胜感激。
(顺便说一句,word_freqs 是由 sklearn 的preprocessing.CountVectorizer() 生成的。如果有解决方案将其转换为另一种矩阵,我当然愿意。)
【问题讨论】:
-
如果
word_freqs是一个 scipy 稀疏矩阵,它应该具有显示形状、非零值数量、dtype 和稀疏格式的打印表示。 -
<18144x14511 sparse matrix of type '<class 'numpy.int64'>' with 619900 stored elements in Compressed Sparse Row format> -
所以它是 .002 稀疏的。
not然后将是所有 99.8% 的。 -
@err1100,你会考虑使用 Pandas.SparseDataFrame 代替 scipy 稀疏矩阵吗?
-
我不会反对,但请参阅下面的评论。我最终需要将它与其他矩阵相乘。我可以用 pandas 做到这一点吗?
标签: python-3.x numpy scipy scikit-learn sparse-matrix