从稀疏转换为密集时,CountVectorizer内存不足



我正试图运行这段代码来计算一堆文档中每个单词的相对频率(很多,超过40000个(,我无法减少词汇表大小,而且在带有12 gb RAM的Colab上运行ign时会出现内存不足错误。我如何重构代码,这样我就不必调用X.toarray((从稀疏转换为密集并抛出内存不足错误(120000个单词*40000个文档(。

vect = CountVectorizer(vocabulary=list(word_to_index.keys()), tokenizer=lambda x: x.split())
X = vect.fit_transform(docs)
X_arr = X.toarray()
rel_freq = np.sum(X_arr, axis=0) / len(docs)
names = vect.get_feature_names()

如果你想知道我为什么需要这样做,是因为我正在实现ConWea代码:https://github.com/dheeraj7596/ConWea数据量比作者大。非常感谢大家。

如果你只需要频率,你可以使用稀疏矩阵的求和方法进行求和:

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = ['This is the first document.','This is the second second document.',
'And the third one.','Is this the first document?']
X = vectorizer.fit_transform(corpus)
X.sum(axis=0)/len(corpus)
matrix([[0.25, 0.75, 0.5 , 0.75, 0.25, 0.5 , 1.  , 0.25, 0.75]])
X.toarray().sum(axis=0)/ len(corpus)
array([0.25, 0.75, 0.5 , 0.75, 0.25, 0.5 , 1.  , 0.25, 0.75])

相关内容

最新更新