ldagibbs-基于LDA的文档分类模型-latent-Dirichlet-allocation-T305

发布时间:2021-03-31 阅读 2482

Stata连享会   主页 || 视频 || 推文 || 知乎

温馨提示: 定期 清理浏览器缓存,可以获得最佳浏览体验。

New! lianxh 命令发布了:
随时搜索推文、Stata 资源。安装命令如下:
. ssc install lianxh
详情参见帮助文件 (有惊喜):
. help lianxh

课程详情 https://gitee.com/lianxh/Course

课程主页 https://gitee.com/lianxh/Course

⛳ Stata 系列推文:

作者:经菠 (中山大学)
邮箱jingb@mail2.sysu.edu.cm

编者按:本文主要摘译自下文,特此致谢!
Source:Schwarz C. ldagibbs: A command for topic modeling in Stata using latent Dirichlet allocation[J]. The Stata Journal, 2018, 18(1): 101-117. -PDF-


目录


1. 问题背景

由于具有多样化和高频等特点,文本数据在经济金融领域得到了广泛的应用。但是对于初学者,文本数据的收集整理还是存在一定难度的。例如,文本数据通常都是一个巨大的语料 (corpora),而语料里面又包含了大量未归类的文档 (document),每份文档里面也有许多词语 (word),如何对文档 (document) 进行聚类 (cluster) 就是一个比较棘手的问题。

为此,本文将介绍一种关于文本聚类的 LDA 主题 (Latent Dirichet Agorithm) 模型、以及 Stata 实现命令 ldagibbs。该模型由 Blei 等 (2003) 提出来的,通过经典算法隐含狄利克雷分布 (Latent Dirichet Allocation) 来判断文档主题,并对文档实现聚类一种的主题模型,属于无监督学习。

2. LDA 模型的基本原理

LDA 模型认为相似主题的文档,往往倾向于使用相似的词语。因此,在同一个主题的文档中,相似的词语应该会共同出现 (co-occour)。LDA 模型主要包括两个部分:

  • 一是建立一个贝叶斯概率模型 (probabilistic model),也就是将整个语料出现的概率表示为一个似然函数;
  • 二是利用近似推断 (approximate inference algorithm) 最大化似然函数。

2.1 建立概率模型

LDA 概率模型假定语料中一共有 D 个文档,每份文档 d 的主题服从由 T 个主题的概率分布。这属于贝叶斯学派的假设,即:

  • 每份文档的主题不是固定的,而是随机的,都有一定概率成为任意的主题;
  • 每份文档主题的概率分布是一个长度为 T 的向量 θT,称为 “文档-主题” 分布。

LDA 模型最后的输出就是 DT 维的矩阵  θ ,其中 p(tt|dd) 表示为文档 d 属于主题 d 的概率。 θ 具体表达式如下:

此外,假设语料中有 V 个不重复的词语 ω,那么在主题 t 时出现词语 ω 的概率记作 p(ωυ|Tt)。“词语-主题” 概率分布矩阵 ϕ 是个 VT 维的矩阵,其表达式如下:

当事先给定参数 θ 和 ϕ 时,LDA 模型假定满足以下的文档生成过程:

  • 给定 “词语-主题” 概率分布矩阵 ϕ,其中 ϕDir(β)Dir(β) 表示参数为 β 的狄利克雷分布;
  • 对于在语料中的每份文档 d
    • 选择每份文档满足的 “文档-主题” 概率分布 θd,其中 θdDir(α)Dir(α) 表示参数为 α 的狄利克雷分布;
    • 文档 d 中假设共有 Nd 个词语,对于每个词语 ωd:首先选择一个主题 zd,n,其中主题服从多项式分布 zd,nmultinomial(θ);其次,再从条件概率 p(ωd,n|zd,n,ϕ) 中选择词语 ωd,n

上述模型中 α 和 β 都属于超参数,需要事前给定,Dir(α) 和 Dir(β) 为共轭分布。对于给定了上述的模型参数之后,整个语料出现的概率表示的似然函数如下:

其中,p(θd|α) 是在给定参数 α 时,对于文档 d 观察到它满足的主题分布为 θd 的概率;p(zd,n|θd) 是在文档 d 的主题分布给定为 θd 时,文档 d 中 n 个词语选择 zn,d 的概率;p(ωd,n|zd,n,ϕ) 是在给定 zn,d 和 ϕ 时,选择词语 ωd,n 的概率。LDA 模型就是根据不断更新 zn,d 和 ϕ 去优化似然函数。

2.2 利用 Gibbs 采样近似推断

Gibbs 采样是一种马尔科夫链算法,也被称为交替条件采样 (alternating conditional sampling)。Gibbs 采样是基于贝叶斯理论,围绕先验知识和观测数据,以观测值作为条件推断出后验分布。Stata 中 WinBUGS 命令能够实现 Gibbs 采样。

由于 Gibbs 采样是一种贝叶斯方法,所以它需要提前给定超参数 α 和 β。 α 主要根据文档中主题的个数 T 所决定,β 则是根据语料中的词语个数所决定。通常当主题个数和词语个数越大时,给定的 α 和 β 就需要越小。Griffiths 和 Steyvers (2004) 建议 α 取 50/T (如果 T 大于 50),β 取 0.1。通常情况下,α 和 β 的初始给定值不会影响到最后的 Gibbs 采样结果。

ldagibss 命令先将文档进行分词处理 (word tokens),然后将分词之后的词语按同样的概率被分配到不同的主题,这提供了初始的 “词语-主题” 分布和 “文档-主题” 分布。

接着,ldagibss 命令对每个词语重新采样新的 “词语-主题” 分布,不过词语分配到主题 T 的概率更新为:

Gibbs 根据每个分词的分配后结果,近似计算 p(ωd,n|zd,n=t,ϕ) 和  p(zd,n=t)。 p(ωd,n|zd,n) 的计算公式如下:

其中,x 为 ωd,n 在话题 t 中出现的次数,Nt 为话题话题 t 中词语数,β 为提前给定的。p(zd,n=t) 计算方法类似。

在每一次循环中,ldagibss 命令都会根据上述概率对每个词语的 “词语-主题” 分布重新分配。上述采样经过几百次循环后,就能收敛。其中 Griffiths 和 Steyvers (2004) 的论文中,经过 150 次循环之后就到达收敛。如果想要进一步分析 LDA 模型的 Gibbs 采样的收敛情况,可以通过 likelihood 选项获取。不过绝大部分的 Gibbs 采样都获得的是局部最大值,而非全局最大值。但是也可以设定不同的随机值,然后比较一下最后的收敛结果。

2.3 补充说明

如果文档比较长的话,建议把文档分成几个段落,再聚类每一个段落。在使用 LDA 模型之前,还需要进行文本预处理,删除无意义的词语或者标点符号,以使聚类效果更优。

理论上, LDA 模型可以应用在任何长度的文本处理中。但是 LDA 模型一般在长度至少为 50-100 个字的文档中表现更好。如果文本长度过低,LDA 模型生成的主题几乎没有意义。

此外 ldagibss 命令还提供了一些基础的文本预处理功能,比如剔除停顿词和过短词语等。如果需要更高级的文本清洗工作的话,可以参考 txttool 命令 (Williams 和 Williams, 2014)。

3. 实际操作

3.1 ldagibbs 命令介绍

命令安装

net install st0515, from(http://www.stata-journal.com/software/sj18-1/) replace

语法介绍


    ldagibbs varname [, options]

    options                         Description
    -----------------------------------------------------------------------------------------
    Gibbs sampler options
      topics(integer)               specify number of topics
      burnin_iter(integer)          specify number of burn-in iterations
      alpha(real)                   set document-topic prior
      beta(real)                    set word-topic prior
      samples(integer)              specify number of samples to take
      sampling_iter(integer)        specify number of iterations between samples
      seed(integer)                 set random seed
      likelihood                    calculate and report likelihood

    Text cleaning options
      min_char(integer)             set minimum number of characters in word
      stopwords(string)             specify stopwords

    Output options
      name_new_var(string)          specify name of new variables
      normalize                     normalize output of ldagibbs
      mat_save                      save word-probability matrix
      path(string)                  specify path in which to save word-probability matrix
    -----------------------------------------------------------------------------------------

其中,主要选项介绍如下:

  • topics(integer):指的是整个语料需要划分成多少个主题,默认值为 10;
  • burnin_iter(integer):指的是 Gibbs 采样经过多少次循环后终止迭代,默认值为 500;
  • alpha(real):指的是超参数 α 的取值,区间为 0 到 1 ,默认值为 0.25;
  • beta(real):指的是超参数 β 的取值,区间为 0 到 1,默认值为 0.1;
  • min_char(integer):移除小于 integer 长度的词语,默认值为 0;
  • stopwords(string):移除停用词,string 为一个词语列表,即在 string 里的所有单词,在 Gibbs 采样过程中都会被移除掉;
  • name_new_var(string):将输出的变量重新命名;
  • normalize:将输出的 “文档-主题” 分布标准化,通常情况下都需要这个 option
  • mat_save:将 “词语-主题” 分布矩阵保存;
  • path(string) 指定 “词语-主题” 分布矩阵保存的路径。

3.2 具体案例分析

在这部分,我们使用的是 1000 条来自美国法庭的法案文本数据,包括每个法案的名字和摘要。

*数据下载
net get st0515.pkg, replace //或通过链接 https://gitee.com/arlionn/data/blob/master/data01/example_data_laws.dta
use example_data_laws.dta, clear

*combine title and summary
generate text_strings = title + " " + summary

*remove nonalphanumerical characters
replace text_strings = ustrregexra(text_strings, "[^a-zA-Z0-9]", " ") //将非字母和数字替换为空格
replace text_strings = stritrim(text_strings) //去除内部多余空格
replace text_strings = strtrim(text_strings)  //去除开头结尾空格
list text_strings if _n<=10
. list text_strings if _n<=10

      +---------------------------------------------------------------------------------------------------------------------------+
      | text_strings                                                                                                              |
      |---------------------------------------------------------------------------------------------------------------------------|
   1. | Social Security and Medicare Lock Box Act of 2001 Requires any Federal budget submitted by the President that recommend.. |
   2. | Economic Growth and Tax Relief Act of 2001 Prohibits minimum bracket amount inflation adjustments through tax year 2006.. |
   3. | Energy Policy Act of 2002 Sec 206 Grants FERC jurisdiction over an electric reliability organization any regional entit.. |
   4. | Reserved for the speaker                                                                                                  |
   5. | Marriage Penalty and Family Tax Relief Act of 2001 Repeals provisions providing for 1 the reduction in the additional c.. |
      |---------------------------------------------------------------------------------------------------------------------------|
   6. | CARE Act of 2002 Sec 103 Sets forth a rule for determining the amount of the deduction allowable for a charitable contr.. |
   7. | Death Tax Elimination Act of 2001 Title III Unified Credit Replaced with Unified Exemption Amount Replaces the unified .. |
   8. | Reserved for the speaker                                                                                                  |
   9. | Railroad Retirement and Survivors Improvement Act of 2001 Sec 102 Repeals the reduction in tier 1 annuity components fo.. |
  10. | Financial Contract Netting Improvement Act of 2001                                                                        |
      +---------------------------------------------------------------------------------------------------------------------------+
*define stopwords
global stopwords "a able about across after all almost also am among an and any are as at be because been but by can cannot could dear did do does either else ever every for from get got had has have he her hers him his how however i if in into is it its just least let like likely may me might most must my neither no nor not of off often on only or other our own rather said say says she should since so some than that the their them then there these they this tis to too twas us wants was we were what when where which while who whom why will with would yet you your"
ldagibbs text_strings, topics(5) alpha(0.25) beta(0.1) seed(3) ///
  burnin_iter(1000) samples(10) sampling_iter(50) min_char(5)  ///
  normalize mat_save stopwords("$stopwords")
  
*list example topics
forvalues i = 1/5{
  gsort -topic_prob`i'
  list title topic_prob`i' if _n<=5, str(45)
}

主题 1 的前五个法案文本数据示例:

. forvalues i = 1/5{
  2.   gsort -topic_prob`i'
  3.   list title topic_prob`i' if _n<=5, str(45)
  4. }

      +-------------------------------------------------------------+
      | title                                             topic_p~1 |
      |-------------------------------------------------------------|
   1. | Omnibus National Heritage Area Act of 2002        .98193548 |
   2. | To amend the Safe and Drug-Free Schools and C..   .96243094 |
   3. | Character Counts for the 21st Century Act         .93869732 |
   4. | Public Education Reinvestment, Reinvention, a..   .93073697 |
   5. | Reading Enrichment After-School Development Act   .92359551 |
      +-------------------------------------------------------------+
*list most frequent words in each topic
wprobimport using "word_prob"
forvalues i=1/5 {
  gsort -word_prob`i'
  list words word_prob`i' if _n<=5
}

主题 1 使用频率最高的五个词语示例:

. forvalues i=1/5 {
  1.   gsort -word_prob`i'
  2.   list words word_prob`i' if _n<=5
  3. }

      +------------------------+
      |      words   word_pr~1 |
      |------------------------|
   1. |  education   .02298982 |
   2. |   national   .02146382 |
   3. |  secretary    .0175276 |
   4. |   programs   .01451838 |
   5. | assistance   .01377678 |
      +------------------------+

4. 参考文献

  • Schwarz C. ldagibbs: A command for topic modeling in Stata using latent Dirichlet allocation[J]. The Stata Journal, 2018, 18(1): 101-117. -PDF-
  • Blei D M, Ng A Y, Jordan M I. Latent dirichlet allocation[J]. the Journal of machine Learning research, 2003, 3: 993-1022. -PDF-
  • Griffiths T L, Steyvers M. Finding scientific topics[J]. Proceedings of the National academy of Sciences, 2004, 101(suppl 1): 5228-5235. -PDF-
  • Williams U, Williams S P. txttool: Utilities for text analysis in Stata[J]. The Stata Journal, 2014, 14(4): 817-829. -PDF-

5. 相关推文

Note:产生如下推文列表的 Stata 命令为:
lianxh lianxh 文本 正则 爬虫, m
安装最新版 lianxh 命令:
ssc install lianxh, replace

相关课程

免费公开课

最新课程-直播课

专题 嘉宾 直播/回看视频
最新专题 文本分析、机器学习、效率专题、生存分析等
研究设计 连玉君 我的特斯拉-实证研究设计-幻灯片-
面板模型 连玉君 动态面板模型-幻灯片-
面板模型 连玉君 直击面板数据模型 [免费公开课,2小时]
  • Note: 部分课程的资料,PPT 等可以前往 连享会-直播课 主页查看,下载。

课程主页

课程主页

关于我们

  • Stata连享会 由中山大学连玉君老师团队创办,定期分享实证分析经验。
  • 连享会-主页知乎专栏,400+ 推文,实证分析不再抓狂。直播间 有很多视频课程,可以随时观看。
  • 公众号关键词搜索/回复 功能已经上线。大家可以在公众号左下角点击键盘图标,输入简要关键词,以便快速呈现历史推文,获取工具软件和数据下载。常见关键词:课程, 直播, 视频, 客服, 模型设定, 研究设计, stata, plus, 绘图, 编程, 面板, 论文重现, 可视化, RDD, DID, PSM, 合成控制法

连享会主页  lianxh.cn
连享会主页 lianxh.cn

连享会小程序:扫一扫,看推文,看视频……

扫码加入连享会微信群,提问交流更方便

✏ 连享会学习群-常见问题解答汇总:
https://gitee.com/arlionn/WD

New! lianxh 命令发布了:
随时搜索连享会推文、Stata 资源,安装命令如下:
. ssc install lianxh
使用详情参见帮助文件 (有惊喜):
. help lianxh