标签: topic-modeling

短文本 Python 主题建模

我想对短文本进行主题建模。我对 LDA 做了一些研究,发现它不太适合短文本。哪些方法会更好?它们有 Python 实现吗?

python nlp python-3.x lda topic-modeling

5
推荐指数
1
解决办法
5001
查看次数

如何使用 PDFPlumber 从两列 PDF 中提取文本

我正在使用 python 进行主题建模任务,我想从年度/可持续性报告中提取文本。然而我的问题是,当我尝试提取报告时,提取的行在页面中的两个不同列之间断开,即它连接相邻段落中的两个不同行以构成一个句子。如何按照报告中的显示方式准确提取行。我已附上报告的版本和函数提取的行。

\n

下面是我使用的函数:

\n

#从url获取pdf的函数

\n
def converter(url):\n    text=[]\n    req= requests.get(url)\n    with pdfplumber.open(BytesIO(req.content)) as pdf:\n        for i in range(0, len(pdf.pages)):\n            pages= pdf.pages[i]\n            text.append(pages.extract_text())\n    return "\\n".join(str(i) for i in text)\n
Run Code Online (Sandbox Code Playgroud)\n

该图像是我正在提取的报告中的一个片段,报告中的文本分为两列,而 extract_content 函数将这两列混合起来得到一行,即将两列中的行连接起来并显示为一行。

\n

这是报告的第一行(第一列和第二列的开头由函数合并在一起):

\n
\n

\\n2019 年我的首要职责之一是接受采访。当我们\n在 2016 年\n开始新的战略时期\xe2\x80\x9c早安挪威\xe2\x80\x9d节目\n进行谈话时,我表示希望AF 会感到 \\n关于 AF\xe2\x80\x99s\n当我们\n希望超越 \\n女性时,将同样紧密结合的百分比增加一倍的目标

\n
\n

如果我能按照报告中给出的确切方式提取句子,那将会很有帮助。

\n

python text-extraction information-extraction topic-modeling pdfplumber

5
推荐指数
1
解决办法
2447
查看次数

将主题建模结果投射到数据框

我用BertTopicwith从一些中KeyBERT提取一些topicsdocs

from bertopic import BERTopic
topic_model = BERTopic(nr_topics="auto", verbose=True, n_gram_range=(1, 4), calculate_probabilities=True, embedding_model='paraphrase-MiniLM-L3-v2', min_topic_size= 3)
topics, probs = topic_model.fit_transform(docs)
Run Code Online (Sandbox Code Playgroud)

现在我可以访问topic name

freq = topic_model.get_topic_info()
print("Number of topics: {}".format( len(freq)))
freq.head(30)

   Topic    Count   Name
0   -1       1     -1_default_greenbone_gmp_manager
1    0      14      0_http_tls_ssl tls_ssl
2    1      8       1_jboss_console_web_application
Run Code Online (Sandbox Code Playgroud)

并检查主题

[('http', 0.0855701486234524),          
 ('tls', 0.061977919455444744),
 ('ssl tls', 0.061977919455444744),
 ('ssl', 0.061977919455444744),
 ('tcp', 0.04551718585531556),
 ('number', 0.04551718585531556)]

[('jboss', 0.14014705432060262),
 ('console', 0.09285308122803233),
 ('web', 0.07323749337563096),
 ('application', 0.0622930523123512),
 ('management', 0.0622930523123512),
 ('apache', 0.05032395169459188)]
Run Code Online (Sandbox Code Playgroud)

我想要的是最终数据, …

nlp python-3.x pandas topic-modeling bert-language-model

5
推荐指数
1
解决办法
575
查看次数

尝试从DocumentTermMatrix中删除单词以使用topicmodel

所以,我正在尝试使用这个topicmodelsR(在6400个文档的语料库中有100个主题,每个约1000个单词).这个过程运行然后死掉,我想因为内存不足.

所以我尝试缩小lda()函数作为输入的文档术语矩阵的大小; 我想我可以minDocFreq在生成文档术语矩阵时使用该函数.但是当我使用它时,它似乎没有任何区别.这是一些代码:

以下是相关的代码:

> corpus <- Corpus(DirSource('./chunks/'),fileEncoding='utf-8')
> dtm <- DocumentTermMatrix(corpus)
> dim(dtm)
[1] 6423 4163
# So, I assume this next command will make my document term matrix smaller, i.e.
# fewer columns. I've chosen a larger number, 100, to illustrate the point.
> smaller <- DocumentTermMatrix(corpus, control=list(minDocFreq=100))
> dim(smaller)
[1]  6423 41613
Run Code Online (Sandbox Code Playgroud)

相同的维度和相同的列数(即相同数量的术语).

我觉得我做错了什么?谢谢.

r topic-modeling tm

4
推荐指数
1
解决办法
5328
查看次数

csvIterator的参数在Mallet中意味着什么?

我正在使用mallet主题建模示例代码,虽然它运行正常,但我想知道这个语句的参数究竟是什么意思?

instances.addThruPipe(new CsvIterator(new FileReader(dataFile),
                                      "(\\w+)\\s+(\\w+)\\s+(.*)",
                                      3, 2, 1)  // (data, target, name) field indices                    
                     );
Run Code Online (Sandbox Code Playgroud)

nlp machine-learning text-analysis mallet topic-modeling

4
推荐指数
1
解决办法
602
查看次数

LDA主题建模输入数据

我是python的新手.我刚刚开始研究在推文上使用LDA主题建模的项目.我正在尝试以下代码:

此示例使用在线数据集.我有一个csv文件,其中包含我需要使用的推文.任何人都可以告诉我如何使用我的本地文件?我该如何制作自己的词汇和标题?

我找不到解释如何为LDA准备材料的教程.他们都假设你已经知道如何这样做.

from __future__ import division, print_function

import numpy as np
import lda
import lda.datasets


# document-term matrix

X = lda.datasets.load_reuters()
print("type(X): {}".format(type(X)))
print("shape: {}\n".format(X.shape))

# the vocab
vocab = lda.datasets.load_reuters_vocab()
print("type(vocab): {}".format(type(vocab)))
print("len(vocab): {}\n".format(len(vocab)))

# titles for each story
titles = lda.datasets.load_reuters_titles()
print("type(titles): {}".format(type(titles)))
print("len(titles): {}\n".format(len(titles)))


doc_id = 0
word_id = 3117

print("doc id: {} word id: {}".format(doc_id, word_id))
print("-- count: {}".format(X[doc_id, word_id]))
print("-- word : {}".format(vocab[word_id]))
print("-- doc  : {}".format(titles[doc_id]))


model = lda.LDA(n_topics=20, n_iter=500, random_state=1)
model.fit(X)


topic_word …
Run Code Online (Sandbox Code Playgroud)

python twitter lda topic-modeling

4
推荐指数
1
解决办法
3681
查看次数

从R中的用户定义语料库中删除停用词

我有一套文件:

documents = c("She had toast for breakfast",
 "The coffee this morning was excellent", 
 "For lunch let's all have pancakes", 
 "Later in the day, there will be more talks", 
 "The talks on the first day were great", 
 "The second day should have good presentations too")
Run Code Online (Sandbox Code Playgroud)

在这组文件中,我想删除停用词.我已经删除了标点并转换为小写,使用:

documents = tolower(documents) #make it lower case
documents = gsub('[[:punct:]]', '', documents) #remove punctuation
Run Code Online (Sandbox Code Playgroud)

首先我转换为Corpus对象:

documents <- Corpus(VectorSource(documents))
Run Code Online (Sandbox Code Playgroud)

然后我尝试删除停用词:

documents = tm_map(documents, removeWords, stopwords('english')) #remove stopwords
Run Code Online (Sandbox Code Playgroud)

但是最后一行会导致以下错误:

调试的THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC().

这已经在这里被问到, …

r topic-modeling tm

4
推荐指数
1
解决办法
3万
查看次数

python scikit learn,在LDA中获取每个主题的文档

我正在使用此处的示例对文本数据执行LDA :我的问题是:
我如何知道哪些文档对应于哪个主题? 换句话说,例如,谈论主题1的文件是什么?

这是我的步骤:

n_features = 1000
n_topics = 8
n_top_words = 20
Run Code Online (Sandbox Code Playgroud)

我逐行阅读我的文本文件:

with open('dataset.txt', 'r') as data_file:
    input_lines = [line.strip() for line in data_file.readlines()]
    mydata = [line for line in input_lines]
Run Code Online (Sandbox Code Playgroud)

打印主题的功能:

def print_top_words(model, feature_names, n_top_words):
    for topic_idx, topic in enumerate(model.components_):
        print("Topic #%d:" % topic_idx)
        print(" ".join([feature_names[i]
                        for i in topic.argsort()[:-n_top_words - 1:-1]]))                        

    print()
Run Code Online (Sandbox Code Playgroud)

对数据进行矢量化:

tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, token_pattern='\\b\\w{2,}\\w+\\b',
                                max_features=n_features,
                                stop_words='english')
tf = tf_vectorizer.fit_transform(mydata)
Run Code Online (Sandbox Code Playgroud)

初始化LDA:

lda = LatentDirichletAllocation(n_topics=3, max_iter=5,
                                learning_method='online',
                                learning_offset=50.,
                                random_state=0)
Run Code Online (Sandbox Code Playgroud)

在tf数据上运行LDA:

lda.fit(tf) …
Run Code Online (Sandbox Code Playgroud)

python machine-learning lda topic-modeling

4
推荐指数
1
解决办法
3273
查看次数

了解LDA /主题建模 - 主题重叠太多

我是主题建模/潜在Dirichlet分配的新手,并且无法理解如何将概念应用于我的数据集(或者它是否是正确的方法).

我有少量的文学文本(小说),并希望使用LDA提取一些一般性主题.

gensim在Python中使用该模块以及一些nltk功能.对于测试,我将原始文本(仅6个)分成30个块,每个块有1000个单词.然后我将块转换为文档项矩阵并运行算法.这是代码(虽然我认为这个问题无关紧要):

# chunks is a 30x1000 words matrix

dictionary = gensim.corpora.dictionary.Dictionary(chunks)
corpus = [ dictionary.doc2bow(chunk) for chunk in chunks ]
lda = gensim.models.ldamodel.LdaModel(corpus = corpus, id2word = dictionary,
    num_topics = 10)
topics = lda.show_topics(5, 5)
Run Code Online (Sandbox Code Playgroud)

然而,结果与我见过的任何一个例子完全不同,主题中充满了无意义的单词,可以在所有源文档中找到,例如"我","他","说","喜欢",......例子:

[(2, '0.009*"I" + 0.007*"\'s" + 0.007*"The" + 0.005*"would" + 0.004*"He"'), 
(8, '0.012*"I" + 0.010*"He" + 0.008*"\'s" + 0.006*"n\'t" + 0.005*"The"'), 
(9, '0.022*"I" + 0.014*"\'s" + 0.009*"``" + 0.007*"\'\'" + 0.007*"like"'), 
(7, '0.010*"\'s" + 0.009*"I" + 0.006*"He" …
Run Code Online (Sandbox Code Playgroud)

python nlp lda gensim topic-modeling

4
推荐指数
1
解决办法
2602
查看次数

ValueError: islice() 的停止参数必须是 None 或整数:0 &lt;= x &lt;= sys.maxsize on topic coherence

我正在关注本教程https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0并找到问题。所以我对这段代码的目的是在主题、alpha 和 beta 参数值的范围内对其进行迭代。所以我可以从 alpha 和 beta 生成的一致性分数中确定最佳主题数

def compute_coherence_values(corpus, dictionary, k, a, b):

lda_model = gensim.models.LdaMulticore(corpus=corpus,
                                       id2word=id2word,
                                       num_topics=10, 
                                       random_state=100,
                                       chunksize=100,
                                       passes=10,
                                       alpha=a,
                                       eta=b,
                                       per_word_topics=True)

coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')

return coherence_model_lda.get_coherence()
Run Code Online (Sandbox Code Playgroud)

进而

import numpy as np
import tqdm
grid = {}
grid['Validation_Set'] = {}
# Topics range
min_topics = 2
max_topics = 11
step_size = 1
topics_range = range(min_topics, max_topics, step_size)
# Alpha parameter
alpha = list(np.arange(0.01, 1, 0.3))
alpha.append('symmetric')
alpha.append('asymmetric')
# Beta parameter
beta = …
Run Code Online (Sandbox Code Playgroud)

python python-itertools python-3.x long-integer topic-modeling

4
推荐指数
1
解决办法
3331
查看次数