NLP LDA 主题模型 实践(使用中文)

NLP LDA 主题模型 实践(使用中文)

使用nltk实现中文主题分类。我的环境是jupyter notebook。
下面是我的程序和文件。
文件目录

E:.
├─.ipynb_checkpoints
├─assets
└─out 

assets 模型训练需要使用的文件
out 模型训练输出的文件
包括数据可视化和日志文件等

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          2022/4/7     14:24           5275 hit_stopwords.txt
-a----          2022/4/7     20:37          78530 test_100.csv
-a----          2022/4/8     15:21         740456 test_1000.csv
-a----          2022/4/8     15:34        7470457 test_10000.csv
-a----          2022/4/8     16:17       75214537 test_100000.csv
-a----          2022/4/8     16:17      147179516 test_200000.csv
-a----          2022/4/8     16:17      213835850 test_300000.csv
-a----          2022/4/7      9:35      231686999 test_all.csv

test_数据条目大小

csv文件内容如下
NLP LDA 主题模型 实践(使用中文)

这里是从微博上爬取的数据。content一列是需要进行主题分析的部分。

html数据可视化运行结果如下
NLP LDA 主题模型 实践(使用中文)

圈的大小,说明了当前主题的重要性。圈越大,当前主题在整个数据集中的占比越大。有几个圈,就有几个主题(topic)。
每一个词语就是一个token。
NLP LDA 主题模型 实践(使用中文)是相关系数。当NLP LDA 主题模型 实践(使用中文)为0 的时候说明当前topic的token与总topic中的token相关为0,即只包含当前topic中的token(红色部分,蓝色部分是总的topic中的token)。当NLP LDA 主题模型 实践(使用中文)为1 的时候说明当前topic的token与总topic中的token相关为1。

模型分析
NLP LDA 主题模型 实践(使用中文)

一般只调整NLP LDA 主题模型 实践(使用中文),即调整NLP LDA 主题模型 实践(使用中文),不调整NLP LDA 主题模型 实践(使用中文)

导入模块

#from gensim.test.utils import common_corpus
#coding: utf-8
import nltk
import re
import numpy as np
import pandas as pd
from pprint import pprint

import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
from gensim.test.utils import datapath
import csv 
import codecs
# spacy for lemmatization
import spacy


# Plotting tools
import pyLDAvis
import pyLDAvis.gensim_models  
# don't skip this gensim
import matplotlib.pyplot as plt
# Enable logging for gensim - optional
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.ERROR)
from textblob import TextBlob
import warnings
warnings.filterwarnings("ignore",category=DeprecationWarning)
from nltk.corpus import stopwords

使用nltk库,jieba库,nltk不支持中文的分词,因此使用jieba代替。

jieba分词和数据清洗部分

import jieba
url = 'test_all'
def proc():
    df = pd.read_csv(f'assets/{url}.csv', encoding='utf-8')
    ls_content = df['content'].values.tolist()

    stopwords_list = []
    with open(r'assets\hit_stopwords.txt', 'r', encoding='utf-8') as f:
        stopwords_list = f.readlines()
    for idx, line in enumerate(stopwords_list):
        stopwords_list[idx] = line[:-1]
        # print(line[:-1])
        # if line.startswith(','):
        # print('___,',idx,line)
#     print(len(stopwords_list))
    stopwords = {}.fromkeys(stopwords_list)
#     print('stopwords', stopwords)
    ls_content_without_stop_words = [['content']]
#     print('ls_content', ls_content)
    for idx, item in enumerate(ls_content):
        segs = jieba.cut(str(item), cut_all=False)
        ls_content_without_stop_words.append([seg.strip() for seg in segs if seg.strip() not in stopwords])
        # print('idx',idx,item)
        # print(ls_content_without_stop_words)
    return ls_content_without_stop_words


hit_stopwords.txt中放的是禁用词

LDA模型参数

k_list = [4,5,11]
data_lemmatized=proc()
id2word = corpora.Dictionary(data_lemmatized)
texts = data_lemmatized
corpus = [id2word.doc2bow(text) for text in texts]
pyLDAvis.enable_notebook()

k_list 表示主题的个数,更换k,即调节NLP LDA 主题模型 实践(使用中文)

LDA模型perplexity指标计算

    lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                               id2word=id2word,
                                               num_topics=topic_k, 
                                               random_state=100,
                                               update_every=1,
                                               chunksize=100,
                                               passes=10,
                                               alpha='auto',
                                               per_word_topics=True)


    print('\nPerplexity:',lda_model.log_perplexity(corpus))

LDA模型coherence指标计算

    coherence_model_lda = CoherenceModel(model=lda_model,texts=data_lemmatized,dictionary=id2word,coherence='c_v')
    coherence_lda = coherence_model_lda.get_coherence()
    print('\nCoherence Score:',coherence_lda)

记录一下计算过程中出现的问题,如果coherence的计算结果为Nan,那么要检查一下保数据集正确。

数据可视化(保存为html):

    # Print the Keyword in the 10 topics
    pprint(lda_model.print_topics())
    doc_lda = lda_model[corpus]

    # Visualize the topics
    vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, id2word)
    pyLDAvis.save_html(vis, f'out/{url}_lda_topic_{topic_k}.html')

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2022年4月11日 下午6:47
下一篇 2022年4月11日 下午6:58

相关推荐