计算LDA内部协方差

import pandas as pd
from gensim import corpora
from gensim.models import LdaModel
from gensim.models.coherencemodel import CoherenceModel
import matplotlib.pyplot as plt

# 读取文本数据
df = pd.read_excel ( '新闻情感分析结果.xlsx' )
combined_texts = df['Combined Text'].tolist ( )

# 准备文档集合
documents = combined_texts

# 构建词袋模型
texts = [[word for word in document.split ( )] for document in documents]
dictionary = corpora.Dictionary ( texts )
corpus = [dictionary.doc2bow ( text ) for text in texts]


# 定义函数计算主题一致性
def calculate_topic_coherence(lda_model, texts, dictionary):
    coherence_model = CoherenceModel ( model=lda_model, texts=texts, dictionary=dictionary, coherence='u_mass' )
    return coherence_model.get_coherence ( )


# 运行代码一次,记录主题一致性结果
num_runs = 10
num_topics_range = range ( 1, 11 )  # 不同主题数量范围

# 创建空列表来存储主题一致性
topic_coherences = []

# 循环不同的主题数量
for num_topics in num_topics_range:
    lda_model = LdaModel ( corpus, num_topics=num_topics, id2word=dictionary, passes=20, iterations=100 )

    # 计算主题一致性并添加到列表中
    coherence = calculate_topic_coherence ( lda_model, texts, dictionary )
    topic_coherences.append ( coherence )

# 绘制图形
plt.plot ( num_topics_range, topic_coherences, marker='o' )
plt.xlabel ( '主题数量' )
plt.ylabel ( '主题一致性' )
plt.title ( '不同主题数量下的主题一致性比较' )
plt.show ( )
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值