import math
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
batch_size,num_steps = 32,35
train_iter,vocab = d2l.load_data_time_machine(batch_size,num_steps)
F.one_hot(torch.tensor([0,2]),len(vocab))
'''
我们每次采样的小批量形状是(批量大小,时间步数)。
one_hot编码将这样的小批量转换成三维张量,最后一个维度等于词表大小(len(vocab))。
我们经常置换输入的维度,以便于获得形状(时间步数,批量大小,词汇表大小)的输出。
这将使得我们更方便地通过最外层的维度,一步一步地更新小批量的隐藏状态。
(想象后面我们训练的时候时输入的每个时间步子上的数据,转置之后的数据方便我们python的读取,有一定的计算加速效果)
'''
X = torch.arange(10).reshape((2, 5))
F.one_hot(X.T, 28).shape
def get_params(vocab_size, num_hiddens, device):
num_inputs = num_outputs = vocab_size
def normal(shape):
return torch.randn(size=shape, device=device) * 0.01
W_xh = normal((num_inputs, num_hiddens))
W_hh = normal((num_hiddens, num_hiddens))
b_h = torch.zeros(num_hiddens, device=device)
W_hq = normal((num_hiddens, num_outputs))
b_q = torch.zeros(num_outputs, device=device)
params = [W_xh, W_hh, b_h, W_hq, b_q]
for param in params:
param.requires_grad_(True)
return params
"""
为了定义循环神经网络模型,我们首先需要一个函数在初始化时返回隐藏状态。
其返回一个张量,全用0填充,其形状为(批量大小,隐藏单元数)。
使用元组可以更容易地处理隐藏状态包含多个变量的情况。
"""
def init_rnn_state(batch_size,num_hiddens,device):
return (torch.zeros((batch_size,num_hiddens),device=device),)
"""
使用rnn函数定义如何在一个时间步计算隐藏状态和输出。
请注意,循环神经网络模型通过最外层维度inputs循环,以便于逐时间步更新小批量的隐藏状态H。
激活函数使用tanh函数。
如多层感知机章节中所述,当元素在实数上均匀分布的时候,tanh的平均值为0
"""
def rnn(inputs, state, params):
W_xh, W_hh, b_h, W_hq, b_q = params
H, = state
outputs = []
for X in inputs:
"""按照时间顺序来遍历数据:首先拿到的是时刻0的批量和词表进行计算"""
H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)
Y = torch.mm(H, W_hq) + b_q
outputs.append(Y)
return torch.cat(outputs, dim=0), (H,)
class RNNModelScratch:
"""从零开始实现的循环神经网络模型"""
def __init__(self, vocab_size, num_hiddens, device, get_params,init_state, forward_fn):
self.vocab_size, self.num_hiddens = vocab_size, num_hiddens
self.params = get_params(vocab_size, num_hiddens, device)
self.init_state, self.forward_fn = init_state, forward_fn
def __call__(self, X, state):
X = F.one_hot(X.T, self.vocab_size).type(torch.float32)
return self.forward_fn(X, state, self.params)
def begin_state(self, batch_size, device):
return self.init_state(batch_size, self.num_hiddens, device)
num_hiddens = 512
net = RNNModelScratch(len(vocab),num_hiddens,d2l.try_gpu(),get_params,init_rnn_state,rnn)
state = net.begin_state(X.shape[0],d2l.try_gpu())
Y,new_state = net(X.to(d2l.try_gpu()),state)
print(Y.shape),print(len(new_state)) , print(new_state[0].shape)
"""
定义预测函数用来生成用户提供的prefix之后的新字符,prefix是一个包含多个字符的字符串。
在prefix中循环遍历这些开始的字符时,不断地将隐藏状态传递到下一个时间步,而不生成任何输出。
这被称为"预热期"(warm-up),在这个期间模型会自我更新(例如,更新隐藏状态),但不进行预测。
预测期之后,隐藏状态比开始的初始值好。
"""
def predict(prefix, num_preds, net, vocab, device):
"""在prefix 后面生成新的字符"""
state = net.begin_state(batch_size=1, device=device)
outputs = [vocab[prefix[0]]]
get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))
for y in prefix[1:]:
_, state = net(get_input(), state)
outputs.append(vocab[y])
for _ in range(num_preds):
y, state = net(get_input(), state)
outputs.append(int(y.argmax(dim=1).reshape(1)))
return "".join([vocab.idx_to_token[i] for i in outputs])
Ans = predict('time traveller ', 10, net, vocab, d2l.try_gpu())
print(Ans)
"""
解决梯度爆炸
"""
def grad_clipping(net, theta):
"""裁剪梯度。"""
if isinstance(net, nn.Module):
params = [p for p in net.parameters() if p.requires_grad]
else:
params = net.params
norm = torch.sqrt(sum(torch.sum((p.grad**2)) for p in params))
if norm > theta:
for param in params:
param.grad[:] *= theta / norm
def train_epoch(net, train_iter, loss, updater, device, use_random_iter):
"""训练模型一个迭代周期。"""
state, timer = None, d2l.Timer()
metric = d2l.Accumulator(2)
for X, Y in train_iter:
if state is None or use_random_iter:
state = net.begin_state(batch_size=X.shape[0], device=device)
else:
if isinstance(net, nn.Module) and not isinstance(state, tuple):
state.detach_()
else:
for s in state:
s.detach_()
y = Y.T.reshape(-1)
X, y = X.to(device), y.to(device)
y_hat, state = net(X, state)
l = loss(y_hat, y.long()).mean()
if isinstance(updater, torch.optim.Optimizer):
updater.zero_grad()
l.backward()
grad_clipping(net, 1)
updater.step()
else:
l.backward()
grad_clipping(net, 1)
updater(batch_size=1)
metric.add(l * y.numel(), y.numel())
return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()
def train(net, train_iter, vocab, lr, num_epochs, device,use_random_iter=False):
"""训练模型"""
loss = nn.CrossEntropyLoss()
animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
legend=['train'], xlim=[10, num_epochs])
if isinstance(net, nn.Module):
updater = torch.optim.SGD(net.parameters(), lr)
else:
updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
predict_train = lambda prefix: predict(prefix, 50, net, vocab, device)
for epoch in range(num_epochs):
ppl, speed = train_epoch(net, train_iter, loss, updater, device,
use_random_iter)
if (epoch + 1) % 10 == 0:
print(predict_train('time traveller'))
animator.add(epoch + 1, [ppl])
print(f'困惑度 {ppl:.1f}, {speed:.1f} 标记/秒 {str(device)}')
print(predict_train('the planet mars i scarcely'))
print(predict_train('scarcely'))
num_epochs, lr = 500, 1
train(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu(),use_random_iter=True)