python lda代码 python做lda分析_建模


主题建模是一种用于找出文档集合中抽象“主题”的统计模型。LDA(Latent Dirichlet Allocation)是主题模型的一个示例,用于将文档中的文本分类为特定的主题。LDA算法为每一个文档构建出一个主题,再为每一个主题添加一些单词,该算法按照Dirichlet分布来建模。
那便开始吧!

数据

在这里将使用到的数据集是15年内发布的100多万条新闻标题的列表,可以从Kaggle下载。


python lda代码 python做lda分析_python lda代码_02


先来看看数据。


python lda代码 python做lda分析_建模_03


1048575


python lda代码 python做lda分析_python实现背景建模方法_04


图1

数据预处理

执行以下步骤:

  • 标记化——将文本分成句子,将句子分成单词,把单词变为小写,去掉标点符号。
  • 删除少于3个字符的单词。
  • 删除所有的句号。
  • 词形还原——将第三人称的单词改为第一人称,将过去和未来时态中的动词改为现在时。
  • 词根化——将单词简化为词根形式。

加载gensim 和nltk库


python lda代码 python做lda分析_python实现背景建模方法_05


[nltk_data] Downloading package wordnet to[nltk_data] C:UsersSusanLiAppDataRoamingnltk_data…[nltk_data] Package wordnet is already up-to-date!True

编写一个函数,对数据集执行词形还原和词干预处理。


python lda代码 python做lda分析_python lda代码_06


预处理之后选择要预览的文档。


python lda代码 python做lda分析_Word_07


源文件:[‘rain’, ‘helps’, ‘dampen’, ‘bushfires’]标记化和词形还原后的文件:[‘rain’, ‘help’, ‘dampen’, ‘bushfir’]成了!预处理标题文本,将结果保存为“processed_docs’


python lda代码 python做lda分析_建模_08


python lda代码 python做lda分析_预处理_09


图2

数据集的词袋

由 “processed_docs”创建一个字典,其中包含单词出现在训练集中的次数。


python lda代码 python做lda分析_建模_10


0 broadcast1 communiti2 decid3 licenc4 awar5 defam6 wit7 call8 infrastructur9 protect10 summit

Gensim filter_extremes

过滤出以下几种情况下的单词:

  • 在少于15个文档中出现(绝对数)或
  • 在总语料库中占比分数超过0.5

以上两步之后,只保留前10万最频繁出现的单词。


python lda代码 python做lda分析_预处理_11


Gensim doc2bow

为每个文档创建一个字典来报告单词和这些单词出现的次数,将其保存到“bow_corpus”,然后再次检查选定的文档。


python lda代码 python做lda分析_预处理_12


[(76, 1), (112, 1), (483, 1), (3998, 1)]

预览样本预处理文件的词袋。


python lda代码 python做lda分析_建模_13


Word 76 (“bushfir”) appears 1 time.Word 112 (“help”) appears 1 time.Word 483 (“rain”) appears 1 time.Word 3998 (“dampen”) appears 1 time.

TF-IDF

利用models.TfidfModel模型,创建 ‘bow_corpus’的 tf-idf模型对象,并将其保存到“tfidf”。对整个语料库进行tfidf转换,并将其命名为“corpus_tfidf’。最后,预览第一份文件的TF-IDF分数值。


python lda代码 python做lda分析_python实现背景建模方法_14


使用词袋运行LDA

使用gensim.models.LdaMulticore训练LDA模型并将其保存到“lda_model’


python lda代码 python做lda分析_预处理_15


计算每个主题下出现的单词及其相对权重。


python lda代码 python做lda分析_python实现背景建模方法_16


python lda代码 python做lda分析_python实现背景建模方法_17


图3
你能用每个主题中的单词及其相应的权重来区分不同的主题吗?

利用TF-IDF 运行LDA


python lda代码 python做lda分析_python实现背景建模方法_18


图4
现在,你能用每个主题中的单词及其相应的权重来区分不同的主题吗?

评估利用LDA词袋模型对样本文档进行分类的效果

检查将测试文件归为哪一类。


python lda代码 python做lda分析_Word_19


python lda代码 python做lda分析_python实现背景建模方法_20


图5
测试文档被模型精确归类为可能性最大的那个主题,说明分类准确。

评估LDA TF-IDF模型对样本文档进行分类的效果


python lda代码 python做lda分析_python实现背景建模方法_21


图6

测试文档被模型精确归类为可能性最大的那个主题,说明分类准确。

隐含文档上的测试模型


python lda代码 python做lda分析_建模_22


图7
源代码可以在GitHub上找到。期待听到您的反馈或问题。

参考资料:

https://www.udacity.com/course/natural-language-processing-nanodegree--nd892