侧边栏壁纸
  • 累计撰写 71 篇文章
  • 累计创建 59 个标签
  • 累计收到 110 条评论

目 录CONTENT

文章目录

Python实现LDA模型

MinChess
2022-04-30 / 0 评论 / 0 点赞 / 533 阅读 / 581 字 / 正在检测是否收录...

lda主题模型

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

示例代码

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

# -*- 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')
0

评论区