前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现LDA模型

Python实现LDA模型

作者头像
MinChess
发布2022-12-26 17:02:07
1.1K0
发布2022-12-26 17:02:07
举报
文章被收录于专栏:九陌斋九陌斋

lda主题模型

文档主题生成模型(Latent Dirichlet Allocation,简称LDA)通常由包含词、主题和文档三层结构组成。LDA模型属于无监督学习技术,它是将一篇文档的每个词都以一定概率分布在某个主题上,并从这个主题中选择某个词语。文档到主题的过程是服从多项分布的,主题到词的过程也是服从多项分布的。

示例代码

目前对lda的理解还不是特别深,分析方法与分析角度的把握暂时也拿不了太准,所以这里暂时记录一个代码,更多的需要进一步学习,比如语义知识处理、根据困惑度确定主题数等各方面内容。

代码语言:javascript
复制
# -*- coding: utf-8 -*-
# @Time : 2022/4/11 11:35
# @Author : MinChess
# @File : lda.py
# @Software: PyCharm 
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

# 读取数据(已分词)
corpus = []

# 读取预料 一行预料为一个文档
for line in open('fenci.txt', 'r',encoding='utf-8').readlines():
    corpus.append(line.strip())

# 计算TF-IDF值
# 设置特征数
n_features = 2000

tf_vectorizer = TfidfVectorizer(strip_accents='unicode',
                                max_features=n_features,
                                stop_words=['的'],
                                max_df=0.99,
                                min_df=0.002)  # 去除文档内出现几率过大或过小的词汇

tf = tf_vectorizer.fit_transform(corpus)

print(tf.shape)
print(tf)

# LDA分析
from sklearn.decomposition import LatentDirichletAllocation

# 设置主题数
n_topics = 2

lda = LatentDirichletAllocation(n_components=n_topics,
                                max_iter=100,
                                learning_method='online',
                                learning_offset=50,
                                random_state=0)
lda.fit(tf)

# 显示主题数 model.topic_word_
print(lda.components_)
# 几个主题就是几行 多少个关键词就是几列
print(lda.components_.shape)

# 计算困惑度
print(u'困惑度:')
print(lda.perplexity(tf, sub_sampling=False))

# 主题-关键词分布
def print_top_words(model, tf_feature_names, n_top_words):
    for topic_idx, topic in enumerate(model.components_):
        print('Topic #%d:' % topic_idx)
        print(' '.join([tf_feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]))
        print("")

# 定义好函数之后 暂定每个主题输出前20个关键词
n_top_words = 20
tf_feature_names = tf_vectorizer.get_feature_names()
# 调用函数
print_top_words(lda, tf_feature_names, n_top_words)

# 可视化分析
import pyLDAvis
import pyLDAvis.sklearn

# pyLDAvis.enable_notebook()

data = pyLDAvis.sklearn.prepare(lda, tf, tf_vectorizer)
print(data)

# 显示图形
# pyLDAvis.show(data)
# pyLDAvis.save_json(data,' fileobj.html')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • lda主题模型
  • 示例代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档