【问题标题】:Select texts by topic (LDA)按主题选择文本 (LDA)
【发布时间】:2020-10-06 16:51:48
【问题描述】:

是否可以查找特定主题(由 LDA 确定)内的文本?

我有一个包含 5 个主题的列表,每个主题 10 个单词,是使用 lda 找到的。

我已经分析了数据框列中的文本。 我想选择/过滤某个特定主题中的行/文本。

如果您需要更多信息,我会提供给您。

我指的是返回此输出的步骤:

[(0,
  '0.207*"house" + 0.137*"apartment" + 0.118*"sold" + 0.092*"beach" + '
  '0.057*"kitchen" + 0.049*"rent" + 0.033*"landlord" + 0.026*"year" + '
  '0.024*"bedroom" + 0.023*"home"'),
 (1,
  '0.270*"school" + 0.138*"homeworks" + 0.117*"students" + 0.084*"teacher" + '
  '0.065*"pen" + 0.038*"books" + 0.022*"maths" + 0.020*"exercise" + '
  '0.020*"friends" + 0.020*"college"'),
 ... ]

创建
# LDA Model

lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                           id2word=id2word,
                                           num_topics=num_topics, 
                                           random_state=100,
                                           update_every=1,
                                           chunksize=100,
                                           passes=10,
                                           alpha='auto', 
                                           # alpha=[0.01]*num_topics,
                                           per_word_topics=True,
                                           eta=[0.01]*len(id2word.keys()))

打印 10 个主题中的关键字

from pprint import pprint
pprint(lda_model.print_topics())
doc_lda = lda_model[corpus]

已分析文本的原始列称为Texts,它看起来像:

Texts 

"Children are happy to go to school..."
"The average price for buying a house is ... "
"Our children love parks so we should consider to buy an apartment nearby"

etc etc...

我的预期输出是

Texts                                            Topic 
    "Children are happy to go to school..."         2
    "The average price for buying a house is ... "  1
    "Our children love parks so we should consider to buy an apartment nearby"                                   

      2

谢谢

【问题讨论】:

    标签: python gensim text-classification lda


    【解决方案1】:

    doc_lda 包含每个句子的 (topic, score) 元组列表。因此,您可以使用任何启发式方法灵活地将主题分配给句子,例如简单的启发式方法会分配具有最高分数的主题。

    我们可以这样提取每个句子的主题分数:

    topic_scores = [[topic_score[1] for topic_score in sent] for sent in doc_lda]
    

    您还可以将上述内容转换为 pandas 数据框,其中每一行是一个句子,每一列是主题 ID。 dataframe 数据结构通常允许对主题分数句子关系进行灵活且更复杂的操作

    df_topics = pd.DataFrame(topic_scores)
    

    如果您只想分配一个句子中得分最高的主题,您可以这样做:

    max_topics = [max(sent, key=lambda x: x[1])[0] for sent in doc_lda]
    

    【讨论】:

    • 我正在关注这个问题,并尝试将您的答案应用于我的数据集。我正在为topic_score in sent] for sent in doc_lda 收到IndexError: list index out of range here [topic_score[1]。您的代码中的sent 是什么?它只是一个变量吗?
    • 是的,它只是一个变量,发送的是doc_lda矩阵中的一行(恰好是一个句子)。
    猜你喜欢
    • 2020-06-29
    • 2021-09-12
    • 1970-01-01
    • 2015-08-19
    • 2017-02-19
    • 2012-03-25
    • 1970-01-01
    • 2015-11-15
    • 2020-12-25
    相关资源
    最近更新 更多