Pandas pd.DataFrame()中的MemoryError

Pandas pd.DataFrame()中的MemoryError,pandas,gensim,lda,topic-modeling,Pandas,Gensim,Lda,Topic Modeling,我有一个df,有2列5百万行,全部为文本(企业的客户评论)。 df.head()产生: df.info() 我正在尝试使用gensim库对df['text']进行主题建模。我尝试先创建一个文档术语矩阵(dtm),然后执行潜在Dirichlet分配(LDA),如下所示: from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords from gensim import m

我有一个df,有2列5百万行,全部为文本(企业的客户评论)。
df.head()
产生:

df.info()

我正在尝试使用gensim库对df['text']
进行主题建模。我尝试先创建一个文档术语矩阵(dtm),然后执行潜在Dirichlet分配(LDA),如下所示:

from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from gensim import matutils, models
import scipy.sparse

cv = CountVectorizer(stop_words='english')
data_cv = cv.fit_transform(df.text)
data_dtm = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names()) #LINE THROWING MemoryError

data_dtm.index = df.index

tdm = data_dtm.transpose()

sparse_counts = scipy.sparse.csr_matrix(tdm)
corpus = matutils.Sparse2Corpus(sparse_counts)

id2word = dict((v, k) for k, v in cv.vocabulary_.items())
lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=2, passes=10)
lda.print_topics()
问题:但是第7行(pd.DataFrame())抛出MemoryError,而我仍然有60%的机器内存可用。即使在df的前100000行上重复该操作,也会得到相同的MemoryError

因为这是主题建模,所以我宁愿一起分析所有行,或者至少分几批分析它们


问题在将
data\u cv
转换为数据帧时,是什么导致Python内存不足?如何克服它?

很可能是
数据\u cv.toarray()
通过将有效的稀疏表示转换为完整/密集数组,对内存扩展负有最大责任

尝试在前一行中的一个单独的临时变量中执行该步骤,以进行检查

但是,如果您的最终目标是进行Gensim LDA分析,那么这些步骤可以很好地使用标记化文本作为输入,因此其他操作(包括
CountVectorizer
以及在数据结构中存储临时结果或大术语文档数组)可能是多余的

例如(忽略任何停止字筛选):

这仍然会在内存中创建两个巨大的
df.text
列副本,一个
标记化文本列表和一个
文本列表,因此它使用的内存超过了最佳值。(对于非常大的语料库,最佳做法是将它们保留在磁盘上,并将它们逐项流到处理步骤中。)

但是,它可能会使用比巨型密集
.toarray()
步骤更少的步骤,甚至不会创建不严格必需的
计数向量器
或临时数组和
数据帧
对象

from gensim.corpora.dictionary import Dictionary
from gensim.models import LdaModel

tokenized_texts = [text_string.split() for text_string in df.text]
texts_dictionary = Dictionary(tokenized_texts)
texts_bows = [texts_dictionary.doc2bow(text_tokens) for text_tokens in tokenized_texts]

lda = LdaModel(corpus=texts_bows, id2word=texts_dictionary, num_topics=2)