重庆网站建设及优化,桂林网站建,如何选择网站公司,网站制作需要哪些8.3.1 学习语言模型
依靠在 8.1 节中对序列模型的分析#xff0c;可以在单词级别对文本数据进行词元化。基本概率规则如下#xff1a; P ( x 1 , x 2 , … , x T ) ∏ t 1 T P ( x t ∣ x 1 , … , x t − 1 ) P(x_1,x_2,\dots,x_T)\prod^T_{t1}P(x_t|x_1,\dots,x_{t-1}) …8.3.1 学习语言模型
依靠在 8.1 节中对序列模型的分析可以在单词级别对文本数据进行词元化。基本概率规则如下 P ( x 1 , x 2 , … , x T ) ∏ t 1 T P ( x t ∣ x 1 , … , x t − 1 ) P(x_1,x_2,\dots,x_T)\prod^T_{t1}P(x_t|x_1,\dots,x_{t-1}) P(x1,x2,…,xT)t1∏TP(xt∣x1,…,xt−1)
例如包含了四个单词的一个文本序列的概率是 P ( d e e p , l e a r n i n g , i s , f u n ) P ( d e e p ) P ( l e a r n i n g ∣ d e e p ) P ( i s ∣ d e e p , l e a r n i n g ) P ( f u n ∣ d e e p , l e a r n i n g , i s ) P(deep,learning,is,fun)P(deep)P(learning|deep)P(is|deep,learning)P(fun|deep,learning,is) P(deep,learning,is,fun)P(deep)P(learning∣deep)P(is∣deep,learning)P(fun∣deep,learning,is)
语言模型就是要计算单词的概率以及给定前面几个单词后出现某个单词的条件概率。这些概率本质上就是语言模型的参数。
假设训练数据集是一个大型的文本语料库。训练数据集中词的概率可以根据给定词的相对词频来计算。对于频繁出现的单词可以统计单词“deep”在数据集中的出现次数然后将其除以整个语料库中的单词总数。接下来尝试估计 P ^ ( l e a r n i n g ∣ d e e p ) n ( d e e p , l e a r n i n g ) n ( d e e p ) \hat{P}(learning|deep)\frac{n(deep,learning)}{n(deep)} P^(learning∣deep)n(deep)n(deep,learning)
其中 n ( x ) n(x) n(x) 和 n ( x , x ′ ) n(x,x) n(x,x′) 分别是单个单词和连续单词对的出现次数。
对于一些不常见的单词组合要想找到足够的出现次数来获得准确的估计可能都不容易。如果数据集很小或者单词非常罕见那么这类单词出现一次的机会可能都找不到。这里一种常见的策略是执行某种形式的拉普拉斯平滑Laplace smoothing具体方法是在所有计数中添加一个小常量。用 n n n 表示训练集中的单词总数用 m m m 表示唯一单词的数量。例如通过 P ^ ( x ) n ( x ) ϵ 1 / m n ϵ 1 P ^ ( x ′ ∣ x ) n ( x , x ′ ) ϵ 2 P ^ ( x ′ ) n ( x ) ϵ 2 P ^ ( x ∣ x , x ′ ) n ( x , x ′ , x ) ϵ 3 P ^ ( x ) n ( x , x ′ ) ϵ 3 \begin{align} \hat{P}(x)\frac{n(x)\epsilon_1/m}{n\epsilon_1}\\ \hat{P}(x|x)\frac{n(x,x)\epsilon_2\hat{P}(x)}{n(x)\epsilon_2}\\ \hat{P}(x|x,x)\frac{n(x,x,x)\epsilon_3\hat{P}(x)}{n(x,x)\epsilon_3} \end{align} P^(x)P^(x′∣x)P^(x∣x,x′)nϵ1n(x)ϵ1/mn(x)ϵ2n(x,x′)ϵ2P^(x′)n(x,x′)ϵ3n(x,x′,x)ϵ3P^(x)
其中 ϵ 1 \epsilon_1 ϵ1 ϵ 2 \epsilon_2 ϵ2 和 ϵ 3 \epsilon_3 ϵ3 是超参数。例如当 ϵ 1 0 \epsilon_10 ϵ10 时不应用平滑当 ϵ 1 \epsilon_1 ϵ1 接近无穷大时 P ^ ( x ) \hat{P}(x) P^(x) 基金均匀概率分布 1 / m 1/m 1/m。
上述方案也存在问题模型很容易变得无效原因如下 需要存储所有的计数 完全忽略了单词的意思。例如“猫”cat和“猫科动物”feline可能出现在相关的上下文中但是想根据上下文调整这类模型其实是相当困难的。 长单词序列大部分是没出现过的因此一个模型如果只是简单地统计先前“看到”的单词序列频率那么模型面对这种问题肯定是表现不佳的。
8.3.2 马尔可夫模型与 n 元语法
如果 P ( x t 1 ∣ x t , … , x 1 ) P ( x t 1 ∣ x t ) P(x_{t1}|x_t,\dots,x_1)P(x_{t1}|x_t) P(xt1∣xt,…,x1)P(xt1∣xt)则序列上的分布满足一阶马尔可夫性质。阶数越高则对应的依赖关系就越长。这种性质可以推导出许多可以应用于序列建模的近似公式 P ( x 1 , x 2 , x 3 , x 4 ) P ( x 1 ) P ( x 2 ) P ( x 3 ) P ( x 4 ) P ( x 1 , x 2 , x 3 , x 4 ) P ( x 1 ) P ( x 2 ∣ x 1 ) P ( x 3 ∣ x 2 ) P ( x 4 ∣ x 3 ) P ( x 1 , x 2 , x 3 , x 4 ) P ( x 1 ) P ( x 2 ∣ x 1 ) P ( x 3 ∣ x 1 , x 2 ) P ( x 4 ∣ x 2 , x 3 ) \begin{align} P(x_1,x_2,x_3,x_4)P(x_1)P(x_2)P(x_3)P(x_4)\\ P(x_1,x_2,x_3,x_4)P(x_1)P(x_2|x_1)P(x_3|x_2)P(x_4|x_3)\\ P(x_1,x_2,x_3,x_4)P(x_1)P(x_2|x_1)P(x_3|x_1,x_2)P(x_4|x_2,x_3) \end{align} P(x1,x2,x3,x4)P(x1,x2,x3,x4)P(x1,x2,x3,x4)P(x1)P(x2)P(x3)P(x4)P(x1)P(x2∣x1)P(x3∣x2)P(x4∣x3)P(x1)P(x2∣x1)P(x3∣x1,x2)P(x4∣x2,x3)
通常涉及一个、两个和三个变量的概率公式分别被称为一元语法unigram、二元语法bigram和三元语法trigram模型。
以下将对模型进行更好的设计。
8.3.3 自然语言统计
import random
import torch
from d2l import torch as d2ltokens d2l.tokenize(d2l.read_time_machine())
corpus [token for line in tokens for token in line] # 将文本行拼接到一起
vocab d2l.Vocab(corpus)
vocab.token_freqs[:10] # 打印前10个频率最高的单词[(the, 2261),(i, 1267),(and, 1245),(of, 1155),(a, 816),(to, 695),(was, 552),(in, 541),(that, 443),(my, 440)]freqs [freq for token, freq in vocab.token_freqs]
d2l.plot(freqs, xlabeltoken: x, ylabelfrequency: n(x),xscalelog, yscalelog)
频率最高的词都是停用词stop words可以被过滤掉。但它们本身仍然是有意义的我们仍然会在模型中使用它们。
此外还有个明显的问题是词频衰减的速度相当地快。从词频图看到词频衰减大致遵循双对数坐标图上的一条直线。这意味着单词的频率满足齐普夫定律Zipf’s law即第 i i i 个最常用单词的频率 n i n_i ni 为 n i ∝ 1 i α n_i\propto\frac{1}{i^\alpha} ni∝iα1
可以等价为 log n i − α log i c \log{n_i}-\alpha\log{i}c logni−αlogic
其中 α \alpha α 是刻画分布的指数 c c c 是常数。
所以上面通过计数统计和平滑来建模单词是不可行的因为这样建模的结果会大大高估尾部也就是所谓的不常用单词的频率。
下面尝试一下二元语法的频率是否与一元语法的频率表现出相同的行为方式。
bigram_tokens [pair for pair in zip(corpus[:-1], corpus[1:])] # 优雅 实在优雅
bigram_vocab d2l.Vocab(bigram_tokens)
bigram_vocab.token_freqs[:10][((of, the), 309),((in, the), 169),((i, had), 130),((i, was), 112),((and, the), 109),((the, time), 102),((it, was), 99),((to, the), 85),((as, i), 78),((of, a), 73)]可以看到二元语法大部分也是两个停用词组成的。下面的三元语法就好些。
trigram_tokens [triple for triple in zip(corpus[:-2], corpus[1:-1], corpus[2:])]
trigram_vocab d2l.Vocab(trigram_tokens)
trigram_vocab.token_freqs[:10][((the, time, traveller), 59),((the, time, machine), 30),((the, medical, man), 24),((it, seemed, to), 16),((it, was, a), 15),((here, and, there), 15),((seemed, to, me), 14),((i, did, not), 14),((i, saw, the), 13),((i, began, to), 13)]bigram_freqs [freq for token, freq in bigram_vocab.token_freqs]
trigram_freqs [freq for token, freq in trigram_vocab.token_freqs]
d2l.plot([freqs, bigram_freqs, trigram_freqs], xlabeltoken: x,ylabelfrequency: n(x), xscalelog, yscalelog,legend[unigram, bigram, trigram])
从这张一元语法、二元语法和三元语法的直观对比图可以看到 除了一元语法词单词序列似乎也遵循齐普夫定律指数的大小受序列长度的影响。 词表中 n 元组的数量并没有那么大这说明语言中存在相当多的结构这些结构给了我们应用模型的希望 很多 n 元组很少出现这使得拉普拉斯平滑非常不适合语言建模。作为代替我们将使用基于深度学习的模型。
8.3.4 读取长序列数据
长序列不能被模型一次性全部处理时依然采用第一节的拆分序列方法。不同的是步长不选择固定的而是从随机偏移量开始划分序列以同时获得覆盖性coverage和随机性randomness。
随机采样
在随机采样中每个样本都是在原始的长序列上任意捕获的子序列。 在迭代过程中来自两个相邻的、随机的、小批量中的子序列不一定在原始序列上相邻。
def seq_data_iter_random(corpus, batch_size, num_steps): #save使用随机抽样生成一个小批量子序列corpus corpus[random.randint(0, num_steps - 1):] # 从头随机截一下保证第一个序列的随机性num_subseqs (len(corpus) - 1) // num_steps # 计算序列数initial_indices list(range(0, num_subseqs * num_steps, num_steps)) # 获取各序列起始下标random.shuffle(initial_indices) # 进行打乱def data(pos):# 返回从pos位置开始的长度为num_steps的序列return corpus[pos: pos num_steps]num_batches num_subseqs // batch_size # 计算组数for i in range(0, batch_size * num_batches, batch_size):# 在这里initial_indices包含子序列的随机起始索引initial_indices_per_batch initial_indices[i: i batch_size] # 截取当前组各序列的启示下标X [data(j) for j in initial_indices_per_batch] # 获取序列作为数据Y [data(j 1) for j in initial_indices_per_batch] # 获取下一个序列作为标签yield torch.tensor(X), torch.tensor(Y)my_seq list(range(35)) # 生成一个从0到34的序列
for X, Y in seq_data_iter_random(my_seq, batch_size2, num_steps5):print(X: , X, \nY:, Y)X: tensor([[18, 19, 20, 21, 22],[13, 14, 15, 16, 17]])
Y: tensor([[19, 20, 21, 22, 23],[14, 15, 16, 17, 18]])
X: tensor([[ 8, 9, 10, 11, 12],[ 3, 4, 5, 6, 7]])
Y: tensor([[ 9, 10, 11, 12, 13],[ 4, 5, 6, 7, 8]])
X: tensor([[23, 24, 25, 26, 27],[28, 29, 30, 31, 32]])
Y: tensor([[24, 25, 26, 27, 28],[29, 30, 31, 32, 33]])顺序分区
在小批量的迭代过程中保留了拆分的子序列的顺序可以保证两个相邻的小批量中的子序列在原始序列上也是相邻的。
def seq_data_iter_sequential(corpus, batch_size, num_steps): #save使用顺序分区生成一个小批量子序列offset random.randint(0, num_steps) # 随机首序列的起始下标num_tokens ((len(corpus) - offset - 1) // batch_size) * batch_size # 计算总词源数Xs torch.tensor(corpus[offset: offset num_tokens]) # 获取词元起始下标Ys torch.tensor(corpus[offset 1: offset 1 num_tokens]) # 获取对应的下一个词元的起始下标Xs, Ys Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1) # 利用矩阵操作分组num_batches Xs.shape[1] // num_steps # 计算组数for i in range(0, num_steps * num_batches, num_steps):X Xs[:, i: i num_steps] # 顺序获取各组作为数据Y Ys[:, i: i num_steps] # 获取下一个序列作为标签yield X, Yfor X, Y in seq_data_iter_sequential(my_seq, batch_size2, num_steps5):print(X: , X, \nY:, Y)X: tensor([[ 5, 6, 7, 8, 9],[19, 20, 21, 22, 23]])
Y: tensor([[ 6, 7, 8, 9, 10],[20, 21, 22, 23, 24]])
X: tensor([[10, 11, 12, 13, 14],[24, 25, 26, 27, 28]])
Y: tensor([[11, 12, 13, 14, 15],[25, 26, 27, 28, 29]])将上述两个采样函数包装到一个类中再定义一个返回数据迭代器和词表的 load 函数。
class SeqDataLoader: #save加载序列数据的迭代器def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):if use_random_iter:self.data_iter_fn d2l.seq_data_iter_randomelse:self.data_iter_fn d2l.seq_data_iter_sequentialself.corpus, self.vocab d2l.load_corpus_time_machine(max_tokens)self.batch_size, self.num_steps batch_size, num_stepsdef __iter__(self):return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)def load_data_time_machine(batch_size, num_steps, #saveuse_random_iterFalse, max_tokens10000):返回时光机器数据集的迭代器和词表data_iter SeqDataLoader(batch_size, num_steps, use_random_iter, max_tokens)return data_iter, data_iter.vocab练习
1假设训练数据集中有 10 万个单词。一个四元语法需要存储多少个词频和相邻多词频率
这应该不好说吧。 2我们如何对一系列对话建模
不会略。 3一元语法、二元语法和三元语法的齐普夫定律的指数是不一样的能设法估计么
不会略。 4想一想读取长序列数据的其他方法
固定最大长度截取多余的部分 5考虑一下我们用于读取长序列的随机偏移量。
a. 为什么随机偏移量是个好主意
b. 它真的会在文档的序列上实现完美的均匀分布吗
c. 要怎么做才能使分布更均匀
总比从头到尾顺着读好。 6如果我们希望一个序列样本是一个完整的句子那么这在小批量抽样中会带来怎样的问题如何解决
不会略。 文章转载自: http://www.morning.wqfj.cn.gov.cn.wqfj.cn http://www.morning.ygrdb.cn.gov.cn.ygrdb.cn http://www.morning.msgnx.cn.gov.cn.msgnx.cn http://www.morning.wgdnd.cn.gov.cn.wgdnd.cn http://www.morning.incmt.com.gov.cn.incmt.com http://www.morning.gfkb.cn.gov.cn.gfkb.cn http://www.morning.sxhdzyw.com.gov.cn.sxhdzyw.com http://www.morning.fbzdn.cn.gov.cn.fbzdn.cn http://www.morning.yydeq.cn.gov.cn.yydeq.cn http://www.morning.ptysj.cn.gov.cn.ptysj.cn http://www.morning.hrypl.cn.gov.cn.hrypl.cn http://www.morning.dwtdn.cn.gov.cn.dwtdn.cn http://www.morning.pxrfm.cn.gov.cn.pxrfm.cn http://www.morning.qqhfc.cn.gov.cn.qqhfc.cn http://www.morning.wanjia-sd.com.gov.cn.wanjia-sd.com http://www.morning.srbfp.cn.gov.cn.srbfp.cn http://www.morning.ddzqx.cn.gov.cn.ddzqx.cn http://www.morning.yjmns.cn.gov.cn.yjmns.cn http://www.morning.gwmny.cn.gov.cn.gwmny.cn http://www.morning.jmmzt.cn.gov.cn.jmmzt.cn http://www.morning.yyzgl.cn.gov.cn.yyzgl.cn http://www.morning.yqqxj1.cn.gov.cn.yqqxj1.cn http://www.morning.hgsmz.cn.gov.cn.hgsmz.cn http://www.morning.nqlcj.cn.gov.cn.nqlcj.cn http://www.morning.nsyzm.cn.gov.cn.nsyzm.cn http://www.morning.wdwfm.cn.gov.cn.wdwfm.cn http://www.morning.ybqlb.cn.gov.cn.ybqlb.cn http://www.morning.cfcpb.cn.gov.cn.cfcpb.cn http://www.morning.gbybx.cn.gov.cn.gbybx.cn http://www.morning.wrbx.cn.gov.cn.wrbx.cn http://www.morning.zgqysw.cn.gov.cn.zgqysw.cn http://www.morning.whothehellami.com.gov.cn.whothehellami.com http://www.morning.hrjrt.cn.gov.cn.hrjrt.cn http://www.morning.mbqyl.cn.gov.cn.mbqyl.cn http://www.morning.clybn.cn.gov.cn.clybn.cn http://www.morning.dbrdg.cn.gov.cn.dbrdg.cn http://www.morning.pzlhq.cn.gov.cn.pzlhq.cn http://www.morning.swkzk.cn.gov.cn.swkzk.cn http://www.morning.kbgzj.cn.gov.cn.kbgzj.cn http://www.morning.rcyrm.cn.gov.cn.rcyrm.cn http://www.morning.qxlyf.cn.gov.cn.qxlyf.cn http://www.morning.hdrrk.cn.gov.cn.hdrrk.cn http://www.morning.rdpps.cn.gov.cn.rdpps.cn http://www.morning.hmdn.cn.gov.cn.hmdn.cn http://www.morning.jbhhj.cn.gov.cn.jbhhj.cn http://www.morning.ktlfb.cn.gov.cn.ktlfb.cn http://www.morning.xcxj.cn.gov.cn.xcxj.cn http://www.morning.sfcfy.cn.gov.cn.sfcfy.cn http://www.morning.bryyb.cn.gov.cn.bryyb.cn http://www.morning.wflsk.cn.gov.cn.wflsk.cn http://www.morning.dlbpn.cn.gov.cn.dlbpn.cn http://www.morning.bbgn.cn.gov.cn.bbgn.cn http://www.morning.pzpj.cn.gov.cn.pzpj.cn http://www.morning.gjxr.cn.gov.cn.gjxr.cn http://www.morning.llyjx.cn.gov.cn.llyjx.cn http://www.morning.zlzpz.cn.gov.cn.zlzpz.cn http://www.morning.xbzfz.cn.gov.cn.xbzfz.cn http://www.morning.yntsr.cn.gov.cn.yntsr.cn http://www.morning.dgxrz.cn.gov.cn.dgxrz.cn http://www.morning.lcxdm.cn.gov.cn.lcxdm.cn http://www.morning.wwznd.cn.gov.cn.wwznd.cn http://www.morning.zyrp.cn.gov.cn.zyrp.cn http://www.morning.lyzwdt.com.gov.cn.lyzwdt.com http://www.morning.c7512.cn.gov.cn.c7512.cn http://www.morning.blqmn.cn.gov.cn.blqmn.cn http://www.morning.nwrzf.cn.gov.cn.nwrzf.cn http://www.morning.nmpdm.cn.gov.cn.nmpdm.cn http://www.morning.mzhhr.cn.gov.cn.mzhhr.cn http://www.morning.brps.cn.gov.cn.brps.cn http://www.morning.dzyxr.cn.gov.cn.dzyxr.cn http://www.morning.touziyou.cn.gov.cn.touziyou.cn http://www.morning.kpbn.cn.gov.cn.kpbn.cn http://www.morning.xlclj.cn.gov.cn.xlclj.cn http://www.morning.rwxnn.cn.gov.cn.rwxnn.cn http://www.morning.xfdkh.cn.gov.cn.xfdkh.cn http://www.morning.dxzcr.cn.gov.cn.dxzcr.cn http://www.morning.dgpxp.cn.gov.cn.dgpxp.cn http://www.morning.qwrb.cn.gov.cn.qwrb.cn http://www.morning.khtyz.cn.gov.cn.khtyz.cn http://www.morning.rqxtb.cn.gov.cn.rqxtb.cn