处理LDA分析中的大量单词(>1亿)时的内存错误处理

2024-04-26 18:09:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有5万个文件-总共有1.62亿字。我想用Gensim做主题建模,类似于本教程here

因此,LDA需要将文档标记成单词,然后创建词频词典。在

因此,我将这些文件读入pandas数据帧中(“content”列包含文本),并执行以下操作以创建文本列表。image of dataframe attached here

texts = [[word for word in row[1]['content'].lower().split() if word not in stopwords] for row in df.iterrows()]

但是,我遇到了一个内存错误,因为字数太大。在

我还尝试了Python中的TokenVectorizer。我也有一个记忆错误。在

def simple_tokenizer(str_input): words = re.sub(r"[^A-Za-z0-9\-]", " ", str_input).lower().split() return words

vectorizer = TfidfVectorizer( use_idf=True, tokenizer=simple_tokenizer, stop_words='english') X = vectorizer.fit_transform(df['content'])

如何处理这些非常长的文档的标记化,使其能够处理为LDA分析?在

我有一个i7,16GB的桌面,如果这很重要的话。在

编辑

因为Python无法存储非常大的列表。实际上,我重写了代码,读取每个文件(最初存储为HTML),将其转换为文本,创建一个文本向量,将其附加到一个列表中,然后将其发送到LDA代码。成功了!在


Tags: 文件in文档标记文本列表forhere
1条回答
网友
1楼 · 发布于 2024-04-26 18:09:12

So, LDA requires one to tokenize the documents into words and then create a word frequency dictionary.

如果您需要的唯一输出是包含单词计数的字典,我将执行以下操作:

循环逐个处理文件。这样你只在内存中存储一个文件。处理它,然后转到下一个:

# for all files in your directory/directories:
with open(current_file, 'r') as f:
    for line in f:
        # your logic to update the dictionary with the word count

# here the file is closed and the loop moves to the next one

编辑:当涉及到在内存中保存一个非常大的字典的问题时,您必须记住Python为保持dict低密度保留了大量内存—这是快速查找的代价。因此,您必须寻找另一种存储键值对的方法,例如元组列表,但是查找的代价会慢得多。This question就是关于这一点的,并且有一些不错的替代品在那里描述。在

相关问题 更多 >