语言模型可以用来评估文本序列是否合理,即计算该序列的概率: P ( w 1 , w 2 , . . . , w T ) P(w_1,w_2,...,w_T) P(w1,w2,...,wT)。其中基于统计的语言模型(马尔科夫链模型)被广泛应用于自然语言处理中。本文将简单介绍下马尔科夫链的理论以及输入数据集的形式。
语言模型
- 语言模型
假设存在序列 ( w 1 , w 2 , . . . , w T ) (w_1,w_2,...,w_T) (w1,w2,...,wT),则其会出现的概率为
P ( w 1 , w 2 , . . . , w T ) = ∏ i = t T P ( w t ∣ w 1 , w 2 , . . . , w t − 1 ) = P ( w 1 ) P ( w 2 ∣ w 1 ) P ( w 3 ∣ w 1 w 2 ) . . . P ( w T ∣ w 1 w 2 . . . w T − 1 ) begin{aligned} P(w_1,w_2,...,w_T)&=prod_{i=t}^{T}{P(w_t|w_1,w_2,...,w_{t-1})}\ &=P(w_1)P(w_2|w_1)P(w_3|w_1w_2)...P(w_T|w_1w_2...w_{T-1}) end{aligned} P(w1,w2,...,wT)=i=t∏TP(wt∣w1,w2,...,wt−1)=P(w1)P(w2∣w1)P(w3∣w1w2)...P(wT∣w1w2...wT−1)
对于具体的某一语料库,词的概率可以通过该词在训练数据集中的相对词频来计算。 - n阶马尔科夫链
上面提出的模型被称为n元语法,这存在两个问题:参数空间过大和数据稀疏。前者指的是如 w 1 w_1 w1和 w 1 w 2 w_1w_2 w1w2等都会组合成一个新的参数,这样搭配出的参数个数将十分巨大;后者指的是具体训练集中很难找到满足 w T w_T wT前有 w 1 , w 2 , . . . , w T − 1 w_1,w_2,...,w_{T-1} w1,w2,...,wT−1的词,词频会很低。要解决这个问题,就要用到马尔科夫假设。
n-1阶马尔科夫链模型是基于这样的假设:当前这个词的出现只跟前面n-1个词的相关。举个栗子,当n=2时: P ( w 3 ∣ w 1 , w 2 ) = P ( w 3 ∣ w 2 ) P(w_3|w_1,w_2)=P(w_3|w_2) P(w3∣w1,w2)=P(w3∣w2)。
输入数据集
- 读取数据集
with open('/home/kesci/input/jaychou_lyrics4703/jaychou_lyrics.txt') as f:
corpus_chars = f.read()
print(len(corpus_chars))
print(corpus_chars[: 40])
corpus_chars = corpus_chars.replace('n', ' ').replace('r', ' ')
corpus_chars = corpus_chars[: 10000]
"""
63282
想要有直升机
想要和你飞到宇宙去
想要和你融化在一起
融化在宇宙里
我每天每天每
"""
- 建立字符索引
idx_to_char = list(set(corpus_chars)) # 去重,得到索引到字符的映射
char_to_idx = {char: i for i, char in enumerate(idx_to_char)} # 字符到索引的映射
vocab_size = len(char_to_idx)
print(vocab_size)
corpus_indices = [char_to_idx[char] for char in corpus_chars] # 将每个字符转化为索引,得到一个索引的序列
sample = corpus_indices[: 20]
print('chars:', ''.join([idx_to_char[idx] for idx in sample]))
print('indices:', sample)
"""
1027
chars: 想要有直升机 想要和你飞到宇宙去 想要和
indices: [1022, 648, 1025, 366, 208, 792, 199, 1022, 648, 641, 607, 625, 26, 155, 130, 5, 199, 1022, 648, 641]
"""
这里需要指出,在前面文本预处理的章节中已经封装了分词、建立映射和转化的工具函数。
时序数据的采样
训练过程每次需要随机读取小批量样本与标签,时序数据的一个样本通常包含连续的字符,这个取决于时间步数的设定。不过对于一个时序数据,长度为T,时间步数为n的情况下,会有T-n个样本,这些样本存在大量的重合,所以需要高效的采样方法,这里介绍两个:随机采样和相邻采样。
- 随机采样
import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
# 减1是因为对于长度为n的序列,X最多只有包含其中的前n - 1个字符
num_examples = (len(corpus_indices) - 1) // num_steps # 下取整,得到不重叠情况下的样本个数
example_indices = [i * num_steps for i in range(num_examples)] # 每个样本的第一个字符在corpus_indices中的下标
print(example_indices)
random.shuffle(example_indices) #随机采样的关键在于这里
print(example_indices)
def _data(i):
# 返回从i开始的长为num_steps的序列
return corpus_indices[i: i + num_steps]
if device is None:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
for i in range(0, num_examples, batch_size):
print(num_examples,batch_size,i)
# 每次选出batch_size个随机样本
batch_indices = example_indices[i: i + batch_size] # 当前batch的各个样本的首字符的下标
X = [_data(j) for j in batch_indices]
Y = [_data(j + 1) for j in batch_indices]
yield torch.tensor(X, device=device), torch.tensor(Y, device=device)
my_seq = list(range(30))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=6):
print('X: ', X, 'nY:', Y, 'n')
"""
[0, 6, 12, 18]
[0, 18, 6, 12]
4 2 0
X: tensor([[ 0, 1, 2, 3, 4, 5],
[18, 19, 20, 21, 22, 23]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[19, 20, 21, 22, 23, 24]])
4 2 2
X: tensor([[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]])
"""
- 相邻采样
def data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None):
if device is None:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
corpus_len = len(corpus_indices) // batch_size * batch_size # 保留下来的序列的长度
corpus_indices = corpus_indices[: corpus_len] # 仅保留前corpus_len个字符
indices = torch.tensor(corpus_indices, device=device)
print(indices)
indices = indices.view(batch_size, -1) # resize成(batch_size, ),相邻采样的关键
print(indices)
batch_num = (indices.shape[1] - 1) // num_steps
print(batch_num)
for i in range(batch_num):
i = i * num_steps
print(i)
X = indices[:, i: i + num_steps]
Y = indices[:, i + 1: i + num_steps + 1]
yield X, Y
my_seq = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=2):
print('X: ', X, 'nY:', Y, 'n')
"""
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tensor([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
2
0
X: tensor([[0, 1],
[5, 6]])
Y: tensor([[1, 2],
[6, 7]])
2
X: tensor([[2, 3],
[7, 8]])
Y: tensor([[3, 4],
[8, 9]])
"""
有些话说
老规矩,问几个问题:
- n元语法语言模型是什么,它的缺点是什么?马尔科夫链是什么?
- 对时间序列数据采样的意义?随机采样与相邻采样实现方式上的区别?yield关键字的作用?
最后
以上就是腼腆睫毛膏最近收集整理的关于动手学深度学习之语言模型与数据集的全部内容,更多相关动手学深度学习之语言模型与数据集内容请搜索靠谱客的其他文章。
发表评论 取消回复