自动补全系统的一个关键组成部分是语言模型。给语言序列分配概率,更容易出现的序列得分越高。例如,“我有一支笔”比“我是一支笔”的概率更高,因为第一个句子在现实世界中更容易出现。
步骤
- 加载和预处理数据
- 加载和tokenize数据
- 把句子分成训练集和测试集。
- 用一个<unk>标记替换低频单词。
- 开发基于N-gram的语言模型
- 从给定的数据集计算n_gram的计数。
- 用k-smoothing估计下一个词的条件概率。
- 通过计算困惑度来评价N-gram模型。
- 根据你的句子,给出接下来的单词的建议。
开发n-gram模型
假设下一个单词的概率只取决于前一个n-gram。
计算条件概率
给定前面n个单词 w t − 1 , w t − 2 ⋯ w t − n w_{t-1}, w_{t-2} \cdots w_{t-n} wt−1,wt−2⋯wt−n,则句中“t”位置的单词的条件概率是:
P
(
w
t
∣
w
t
−
1
…
w
t
−
n
)
(1)
P(w_t | w_{t-1}\dots w_{t-n}) \tag{1}
P(wt∣wt−1…wt−n)(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^(wt∣wt−1…wt−n)=C(wt−1…wt−n)C(wt−1…wt−n,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^(wt∣wt−1…wt−n)=C(wt−1…wt−n)+k∣V∣C(wt−1…wt−n,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+1∏NP(wt∣wt−n⋯wt−1)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=n∏N−1P(wt∣wt−n⋯wt−1)1(4.1)
概率越高,困惑就越低。
构建自动补全系统
计算所有可能的下一个单词的概率,并建议最有可能的单词。此函数还采用可选参数start_with,它指定下一个单词的前几个字母。
estimate_probabilities返回一个字典,其中key是单词,value是单词的概率。