使用LDA模型提取政策主题

一.LDA模型介绍

Latent Dirichlet Allocation (LDA) 是一种生成式概率模型,常用于主题模型。其主要目的是从大量文档中自动提取隐藏的主题。LDA假设每个文档由多个主题组成,每个主题由一组词汇以不同的概率分布组成。LDA模型通过以下步骤工作:

  1. 文档生成过程

    • 每个文档被视为若干主题的混合。
    • 每个主题由一组单词组成,且这些单词以不同的概率出现。
    • 通过不断迭代,LDA模型能够推断出这些隐藏的主题及其相关的词汇分布。
  2. 模型训练

    • LDA模型使用EM算法(Expectation-Maximization)进行参数估计,寻找最优的主题-词分布和文档-主题分布。
  3. 应用场景

    • LDA模型常用于文本分类、信息检索、推荐系统等领域,能够帮助理解大规模文本数据的潜在结构和主题分布。

二.代码展示(对两会政策的主题提取) 


from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import pandas as pd

# Load the Excel file with policy names
excel_path = '/mnt/data/fkn.xlsx'
df_policies = pd.read_excel(excel_path)

# Display the first few rows of the dataframe
df_policies.head()
# Extract policy names
policy_names = df_policies['政策名称'].astype(str)

# Vectorize the policy names using CountVectorizer
vectorizer = CountVectorizer(max_df=0.95, min_df=2, token_pattern=r'[\u4e00-\u9fa5]+')
policy_matrix = vectorizer.fit_transform(policy_names)

# Fit the LDA model
lda = LatentDirichletAllocation(n_components=5, random_state=42)
lda.fit(policy_matrix)

# Extract topics
n_top_words = 10
feature_names = vectorizer.get_feature_names_out()

# Function to display topics
def display_topics(model, feature_names, n_top_words):
    topics = {}
    for topic_idx, topic in enumerate(model.components_):
        topic_words = [feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]
        topics[f"Topic {topic_idx + 1}"] = ', '.join(topic_words)
    return topics

# Get the topics
topics = display_topics(lda, feature_names, n_top_words)

# Convert the topics to a DataFrame
df_topics = pd.DataFrame(topics.items(), columns=['Topic', 'Top Words'])

# Save the topics to an Excel file
topics_output_path = '/mnt/data/policy_topics.xlsx'
df_topics.to_excel(topics_output_path, index=False)

# Confirm the path of the saved topics
topics_output_path

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值