2.1 文本预处理
神经网络不能直接处理字符串,所以要转化为数值的形式。文本预处理一般包含四个步骤:读入,分词,建立字典,将文本由词的序列转化为索引的序列。
读入文本
import collections
import re
def read_time_machine():
with open('timemachine.txt', 'r') as f:
#用正则表达式把由非小写字母构成的非空字符串替换为空格
#去掉前后缀的空白字符,并且把大写转化为小写
lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
return lines
lines = read_time_machine()
分词
def tokenize(sentences, token='word'):
#token是指标志,意思是作什么级别的分词
"""Split sentences into word or char tokens"""
if token == 'word':
return [sentence.split(' ') for sentence in sentences]
elif token == 'char':
return [list(sentence) for sentence in sentences]
else:
print('ERROR: unkown token type '+token)
tokens = tokenize(lines)
tokens[0:2]
建立字典。将每个词映射为唯一的索引编号。
class Vocab(object):
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
#min_freq是阈值,对于小于该阈值的词可忽略
counter = count_corpus(tokens) #统计词频
self.token_freqs = list(counter.items())
self.idx_to_token = []
if use_special_tokens:
#pad:补充在短的句子上;bos:句子开始;eos:句子结束;unk:不在语料库的未登录词
self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
self.idx_to_token += ['pad', 'bos', 'eos', 'unk']
else:
self.unk = 0
self.idx_to_token += ['unk']
self.idx_to_token += [token for token, freq in self.token_freqs
if freq >= min_freq and token not in self.idx_to_token] #后面用于防止语料库中真的有这个词
self.token_to_idx = dict()
for idx, token in enumerate(self.idx_to_token):
self.token_to_idx[token] = idx
def __len__(self):
return len(self.idx_to_token)
def __getitem__(self, tokens):
#定义索引
if not isinstance(tokens, (list, tuple)):
return self.token_to_idx.get(tokens, self.unk)
return [self.__getitem__(token) for token in tokens]
def to_tokens(self, indices):
#给定索引返回对应的词
if not isinstance(indices, (list, tuple)):
return self.idx_to_token[indices]
return [self.idx_to_token[index] for index in indices]
def count_corpus(sentences):
tokens = [tk for st in sentences for tk in st]
return collections.Counter(tokens) # 返回一个字典,记录每个词的出现次数
上面的分词方式还比较简单。有以下几个缺点:舍弃了标点符号带来的语义信息,类似“shouldn’t”,“doesn’t”,"Mr."这样的词会被错误处理掉。
可用一些现有的工具更好地进行分词,例如spaCy, NLTK。
2.2 语言模型
语言模型对于给定的一段序列,判断该序列合不合理,即计算概率。
假设序列
w
1
,
w
2
,
…
,
w
T
w_1,w_2,\dots,w_T
w1,w2,…,wT是依次生成的,
P
(
w
1
,
w
2
,
…
,
w
T
)
=
P
(
w
1
)
P
(
w
2
∣
w
1
)
…
P
(
w
T
∣
w
1
…
w
T
−
1
)
P(w_1,w_2,\dots,w_T)=P(w_1)P(w_2|w_1)\dots P(w_T|w_1\dots w_{T-1})
P(w1,w2,…,wT)=P(w1)P(w2∣w1)…P(wT∣w1…wT−1)
语言模型的参数就是词的概率以及给定前几个词情况下的条件概率。例如
P
(
w
1
)
=
n
(
w
1
)
n
P(w_1)=\frac{n(w_1)}{n}
P(w1)=nn(w1)
n
(
w
1
)
n(w_1)
n(w1)是语料库中以
w
1
w_1
w1为第一个词的文本数量,
n
n
n是语料库中文本总数。
n元语法
由于随着序列长度的增加计算和存储多个词共同出现的概率复杂度也会增加。n元语法通过马尔科夫假设简化模型,马尔科夫假设是指一个词的出现只与前面n个词有关。基于n-1阶马尔科夫链,可将语言模型改写为
P
(
w
1
,
w
2
,
…
,
w
T
)
=
∏
t
=
1
T
P
(
w
t
∣
w
t
−
(
n
−
1
)
,
…
,
w
t
−
1
)
P(w_1,w_2,\dots,w_T)=\prod_{t=1}^TP(w_t|w_{t-(n-1)},\dots, w_{t-1})
P(w1,w2,…,wT)=t=1∏TP(wt∣wt−(n−1),…,wt−1)
当n较大时,要维护的参数数量会呈指数增长。而且还有数据过于稀疏的缺陷,因为大部分的单词的词频都比较小。
建立字符索引的函数
def load_data_jay_lyrics():
with open('jaychou_lyrics.txt') as f:
corpus_chars = f.read()
corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')
corpus_chars = corpus_chars[0:10000]
idx_to_char = list(set(corpus_chars))
char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)])
vocab_size = len(char_to_idx)
corpus_indices = [char_to_idx[char] for char in corpus_chars]
return corpus_indices, char_to_idx, idx_to_char, vocab_size#最后是语料的索引序列的字符大小
在训练中选取小批量的样本。这是具有连续字符的时序数据,可采用随机采样和相邻采样。
随机采样中每个样本是随意截取的一段
import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
#batch_size是指批量大小
# 减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中的下标
random.shuffle(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):
# 每次选出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)
相邻抽样中两个随机小批量在原始序列中位置相毗邻
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)
indices = indices.view(batch_size, -1) # resize成(batch_size, )
batch_num = (indices.shape[1] - 1) // num_steps
for i in range(batch_num):
i = i * num_steps
X = indices[:, i: i + num_steps]
Y = indices[:, i + 1: i + num_steps + 1]
yield X, Y
2.3 循环神经网络
基于当前的输出与过去的输入序列预测下一个字符。循环神经网络引入一个隐藏变量H,用
H
t
H_t
Ht表示H在时间步t的值
H
t
=
ϕ
(
X
t
W
x
h
+
H
t
−
1
W
h
h
+
b
h
)
H_t=\phi(X_tW_{xh}+H_{t-1}W_{hh}+b_h)
Ht=ϕ(XtWxh+Ht−1Whh+bh)
其中
ϕ
\phi
ϕ是非线性激活函数。上式的计算是循环的。在时间t,输出层的输出为
O
t
=
H
t
W
h
q
+
b
q
O_t=H_tW_{hq}+b_q
Ot=HtWhq+bq
要将字符表示为one-hot向量,即在字符索引位置为1,其余为0的向量
def one_hot(x, n_class, dtype=torch.float32):
result = torch.zeros(x.shape[0], n_class, dtype=dtype, device=x.device) # shape: (n, n_class)
result.scatter_(1, x.long().view(-1, 1), 1) # result[i, x[i, 0]] = 1
return result
#将采用的小批量转换为矩阵
def to_onehot(X, n_class):
return [one_hot(X[:, i], n_class) for i in range(X.shape[1])]
定义模型
def rnn(inputs, state, params):
# inputs和outputs皆为num_steps个形状为(batch_size, vocab_size)的矩阵
#state是计算过程中要维护的状态,保存了初始值
W_xh, W_hh, b_h, W_hq, b_q = params
H, = state
outputs = []
for X in inputs:
H = torch.tanh(torch.matmul(X, W_xh) + torch.matmul(H, W_hh) + b_h)
Y = torch.matmul(H, W_hq) + b_q
outputs.append(Y)
return outputs, (H,)#可用作下一个状态的初始值
def init_rnn_state(batch_size, num_hiddens, device):
return (torch.zeros((batch_size, num_hiddens), device=device), )
因为通过时间反向传播,循环神经网络中较容易出现梯度衰减或梯度爆炸,可用梯度裁剪应对。把所有模型参数的梯度拼接为向量
g
g
g,并设裁剪的阈值
θ
\theta
θ,裁剪后梯度
m
i
n
(
θ
∣
∣
g
∣
∣
,
1
)
g
min(\frac{\theta}{||g||},1)g
min(∣∣g∣∣θ,1)g
def grad_clipping(params, theta, device):
#theta是阈值
norm = torch.tensor([0.0], device=device)#记录所有梯度的L2范数
for param in params:
norm += (param.grad.data ** 2).sum()
norm = norm.sqrt().item()#得到g的L2范数
if norm > theta:
for param in params:
param.grad.data *= (theta / norm)
定义预测函数`
def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,
num_hiddens, vocab_size, device, idx_to_char, char_to_idx):
state = init_rnn_state(1, num_hiddens, device)
output = [char_to_idx[prefix[0]]] # output记录prefix加上预测的num_chars个字符
for t in range(num_chars + len(prefix) - 1):
# 将上一时间步的输出作为当前时间步的输入
X = to_onehot(torch.tensor([[output[-1]]], device=device), vocab_size)
# 计算输出和更新隐藏状态
(Y, state) = rnn(X, state, params)
# 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符
if t < len(prefix) - 1:
output.append(char_to_idx[prefix[t + 1]])
else:
output.append(Y[0].argmax(dim=1).item())
return ''.join([idx_to_char[i] for i in output])
通常使用困惑度来评价语言模型的好坏。困惑度是对交叉熵损失函数做指数运算得到的值,也是标签类别的概率的倒数。最佳情况下,模型对标签类别的概率预测为1,困惑度为1。
模型训练
def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
vocab_size, device, corpus_indices, idx_to_char,
char_to_idx, is_random_iter, num_epochs, num_steps,
lr, clipping_theta, batch_size, pred_period,
pred_len, prefixes):
#判断使用哪种采样方法
if is_random_iter:
data_iter_fn = d2l.data_iter_random
else:
data_iter_fn = d2l.data_iter_consecutive
params = get_params()
loss = nn.CrossEntropyLoss()
#训练过程
for epoch in range(num_epochs):
if not is_random_iter: # 如使用相邻采样,在epoch开始时初始化隐藏状态
state = init_rnn_state(batch_size, num_hiddens, device)
l_sum, n, start = 0.0, 0, time.time()
data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device)
for X, Y in data_iter:
if is_random_iter: # 如使用随机采样,在每个小批量更新前初始化隐藏状态
state = init_rnn_state(batch_size, num_hiddens, device)
else: # 否则需要使用detach函数从计算图分离隐藏状态
for s in state:
s.detach_()
# inputs是num_steps个形状为(batch_size, vocab_size)的矩阵
inputs = to_onehot(X, vocab_size)
# outputs有num_steps个形状为(batch_size, vocab_size)的矩阵
(outputs, state) = rnn(inputs, state, params)
# 拼接之后形状为(num_steps * batch_size, vocab_size)
outputs = torch.cat(outputs, dim=0)
# Y的形状是(batch_size, num_steps),转置后再变成形状为
# (num_steps * batch_size,)的向量,这样跟输出的行一一对应
y = torch.flatten(Y.T)
# 使用交叉熵损失计算平均分类误差
l = loss(outputs, y.long())
#反向传播
# 梯度清0
if params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
grad_clipping(params, clipping_theta, device) # 裁剪梯度
d2l.sgd(params, lr, 1) # 因为误差已经取过均值,梯度不用再做平均
l_sum += l.item() * y.shape[0]
n += y.shape[0]
if (epoch + 1) % pred_period == 0:
print('epoch %d, perplexity %f, time %.2f sec' % (
epoch + 1, math.exp(l_sum / n), time.time() - start))
for prefix in prefixes:
print(' -', predict_rnn(prefix, pred_len, rnn, params, init_rnn_state,
num_hiddens, vocab_size, device, idx_to_char, char_to_idx))