【问题标题】:CountVectorizer running out of memory when converting from sparse to dense从稀疏转换为密集时,CountVectorizer 内存不足
【发布时间】:2021-03-07 12:08:46
【问题描述】:

我正在尝试运行此代码来计算一堆文档中每个单词的相对频率(很多,超过 40000),我无法减少词汇量,并且在 Colab 上运行时会抛出内存不足错误配备 12 GB 内存。 如何重构代码,这样我就不必调用 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 数据量比作者多。 非常感谢大家。

【问题讨论】:

  • 尝试参数max_df和/或min_df

标签: python scikit-learn nlp out-of-memory text-classification


【解决方案1】:

如果只需要频率,可以用sum method求稀疏矩阵求和:

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])

【讨论】:

  • 这很棒,效果很好,我也应该告诉论文作者
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 2013-10-17
  • 2021-09-05
  • 2015-09-14
  • 2022-01-05
  • 2016-09-09
  • 1970-01-01
  • 2017-05-10
相关资源
最近更新 更多