NLP-C2-W3-N-gram和自动补全

自动补全系统的一个关键组成部分是语言模型。给语言序列分配概率,更容易出现的序列得分越高。例如,“我有一支笔”比“我是一支笔”的概率更高,因为第一个句子在现实世界中更容易出现。

步骤

  1. 加载和预处理数据
    • 加载和tokenize数据
    • 把句子分成训练集和测试集。
    • 用一个<unk>标记替换低频单词。
  2. 开发基于N-gram的语言模型
    • 从给定的数据集计算n_gram的计数。
    • 用k-smoothing估计下一个词的条件概率。
  3. 通过计算困惑度来评价N-gram模型。
  4. 根据你的句子,给出接下来的单词的建议。

开发n-gram模型

假设下一个单词的概率只取决于前一个n-gram。

计算条件概率

给定前面n个单词 w t − 1 , w t − 2 ⋯ w t − n w_{t-1}, w_{t-2} \cdots w_{t-n} wt1,wt2wtn,则句中“t”位置的单词的条件概率是:

P ( w t ∣ w t − 1 … w t − n ) (1) P(w_t | w_{t-1}\dots w_{t-n}) \tag{1} P(wtwt1wtn)(1)
可以通过计算训练数据中这些单词序列的出现次数来估计这种概率。
概率可以用比率来估计,其中:
分子是训练数据中单词t-1到t-n之后“t”位置出现该单词的次数。
分母是单词t-1到t-n在训练数据中出现的次数。
P ^ ( w t ∣ w t − 1 … w t − n ) = C ( w t − 1 … w t − n , w n ) C ( w t − 1 … w t − n ) (2) \hat{P}(w_t | w_{t-1}\dots w_{t-n}) = \frac{C(w_{t-1}\dots w_{t-n}, w_n)}{C(w_{t-1}\dots w_{t-n})} \tag{2} P^(wtwt1wtn)=C(wt1wtn)C(wt1wtn,wn)(2)

P ^ \hat{P} P^ 表示 P P P的估计.
Notice that denominator of the equation (2) is the number of occurence of the previous n n n words, and the numerator is the same sequence followed by the word w t w_t wt.

K-smoothing

K-smoothing adds a positive constant k k k to each numerator and k × ∣ V ∣ k \times |V| k×V in the denominator, where ∣ V ∣ |V| V is the number of words in the vocabulary.
P ^ ( w t ∣ w t − 1 … w t − n ) = C ( w t − 1 … w t − n , w n ) + k C ( w t − 1 … w t − n ) + k ∣ V ∣ (3) \hat{P}(w_t | w_{t-1}\dots w_{t-n}) = \frac{C(w_{t-1}\dots w_{t-n}, w_n) + k}{C(w_{t-1}\dots w_{t-n}) + k|V|} \tag{3} P^(wtwt1wtn)=C(wt1wtn)+kVC(wt1wtn,wn)+k(3)

The equation (2) tells us that to estimate probabilities based on n-grams, you need the counts of n-grams (for denominator) and (n+1)-grams (for numerator).

计数和概率矩阵

正如我们到目前为止所看到的,上面计算的n-gram计数足以计算下一个单词的概率。将它们表示为计数或概率矩阵可能更直观。

在这里插入图片描述

计算困惑度

困惑度被用作语言模型的评估指标。要计算n-gram模型上测试集的困惑度,请使用:
P P ( W ) = ∏ t = n + 1 N 1 P ( w t ∣ w t − n ⋯ w t − 1 ) N (4) PP(W) =\sqrt[N]{ \prod_{t=n+1}^N \frac{1}{P(w_t | w_{t-n} \cdots w_{t-1})} } \tag{4} PP(W)=Nt=n+1NP(wtwtnwt1)1 (4)
where N N N is the length of the sentence.
n n n is the number of words in the n-gram (e.g. 2 for a bigram).
In math, the numbering starts at one and not zero.
In code, array indexing starts at zero, so the code will use ranges for t t t according to this formula:

P P ( W ) = ∏ t = n N − 1 1 P ( w t ∣ w t − n ⋯ w t − 1 ) N (4.1) PP(W) =\sqrt[N]{ \prod_{t=n}^{N-1} \frac{1}{P(w_t | w_{t-n} \cdots w_{t-1})} } \tag{4.1} PP(W)=Nt=nN1P(wtwtnwt1)1 (4.1)
概率越高,困惑就越低。

在这里插入图片描述

构建自动补全系统

计算所有可能的下一个单词的概率,并建议最有可能的单词。此函数还采用可选参数start_with,它指定下一个单词的前几个字母。

estimate_probabilities返回一个字典,其中key是单词,value是单词的概率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值