RNN循环神经网络python实现

2023-12-15 02:12:46
import collections
import math
import re
import random
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l


def read_txt():
    # 读取文本数据
    with open('./A Study in Drowning.txt', 'r', encoding='utf-8') as f:
        # 读取每一行
        lines = f.readlines()
    # 将不是英文字符的转换为空格,全部变为小写字符返回
    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]


def tokenize(lines, token='word'):
    # 将文本以空格进行分割成词
    if token == 'word':
        return [line.split() for line in lines]
    # 将文本分割成字符
    elif token == 'char':
        return [list(line) for line in lines]
    else:
        print('错误:未知令牌类型:' + token)


def count_corpus(tokens):
    # 如果tokens长度为0或tokens[0]是list
    if len(tokens) == 0 or isinstance(tokens[0], list):
        # 将[[,,,],[,,,]]多层结构变为一层结构[,,,,]
        tokens = [token for line in tokens for token in line]
    # 统计可迭代对象中元素出现的次数,并返回一个字典(key-value)key 表示元素,value 表示各元素 key 出现的次数
    return collections.Counter(tokens)


# idx_to_token  是一个list  由token作为元素构成['<unk>', ' ', 'e', 't', 'a', 'o', 'h', 'n', 'i', 's', 'r', 'd', 'l', 'u', 'f', 'w', 'g', 'm', 'y', 'c', 'p', 'b', 'k', 'v', 'j', 'x', 'z', 'q']
# token_freqs   是一个list  由token和该token出现的次数构成的元组作为元素构成[(' ', 94824), ('e', 54804), ('t', 38742), ('a', 33172), ('o', 30656), ('h', 29047), ('n', 28667), ('i', 28093), ('s', 27922), ('r', 26121), ('d', 20394), ('l', 17755), ('u', 12267), ('f', 11033), ('w', 10033), ('g', 9837), ('m', 9258), ('y', 9251), ('c', 8872), ('p', 6998), ('b', 6620), ('k', 4817), ('v', 3574), ('j', 500), ('x', 372), ('z', 308), ('q', 285)]
# token_to_idx  是一个dict  由token作为key token在idx_to_token的索引作为value构成{' ': 1, '<unk>': 0, 'a': 4, 'b': 21, 'c': 19, 'd': 11, 'e': 2, 'f': 14, 'g': 16, 'h': 6, 'i': 8, 'j': 24, 'k': 22, 'l': 12, 'm': 17, 'n': 7, 'o': 5, 'p': 20, 'q': 27, 'r': 10, 's': 9, 't': 3, 'u': 13, 'v': 23, 'w': 15, 'x': 25, 'y': 18, 'z': 26}
class Vocab:
    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):
        # 处理特殊情况
        if tokens is None:
            tokens = []
        # 处理特殊情况
        if reserved_tokens is None:
            reserved_tokens = []
        # counter为一个字典(key-value)key 表示元素,value 表示各元素 key 出现的次数
        counter = count_corpus(tokens)
        # 排序
        # iterable:待排序的序列counter.items()
        # key:排序规则lambda x: x[1]从小到大
        # reverse:指定排序的方式,默认值False,即升序排列,这是True也就是降序
        self.token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True)
        # 初始化
        self.unk, uniq_tokens = 0, ['<unk>'] + reserved_tokens
        # 初始化  token_freqs中 key不在 uniq_tokens中  且  value大于min_freq 返回token放入uniq_tokens
        uniq_tokens += [
            token for token, freq in self.token_freqs
            if freq >= min_freq and token not in uniq_tokens]
        # 初始化
        self.idx_to_token, self.token_to_idx = [], dict()
        # 赋值
        for token in uniq_tokens:
            self.idx_to_token.append(token)
            self.token_to_idx[token] = len(self.idx_to_token) - 1

    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 load_corpus_time_machine(max_tokens=-1):
    # 将文本处理成行
    lines = read_txt()
    # print(lines)
    # 将行tokens化
    tokens = tokenize(lines, 'char')
    # print(tokens)
    # 构建字典表
    vocab = Vocab(tokens)
    # vocab的格式为{list:524222}[5, 7, 2, 5, 7, 2, 8, 3, ......, 1, 18, 5, 13]
    #print(vocab)
    corpus = [vocab[token] for line in tokens for token in line]
    if max_tokens > 0:
        corpus = corpus[:max_tokens]
    return corpus, vocab


# 随机地生成一个小批量数据的特征和标签以供读取。 在随机采样中,每个样本都是在原始的长序列上任意捕获的子序列
def seq_data_iter_random(corpus, batch_size, num_steps):
    """使用随机抽样生成一个小批量子序列。"""
    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):
        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_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)


# 保证两个相邻的小批量中的子序列在原始序列上也是相邻的
def seq_data_iter_sequential(corpus, batch_size, num_steps):
    """使用顺序分区生成一个小批量子序列。"""
    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, Y


class SeqDataLoader:
    """加载序列数据的迭代器。"""
    def __init__(self, batch_size, num_steps, use_random_iter, max_tokens):
        if use_random_iter:
            self.data_iter_fn = seq_data_iter_random
        else:
            self.data_iter_fn = seq_data_iter_sequential
        self.corpus, self.vocab = load_corpus_time_machine(max_tokens)
        self.batch_size, self.num_steps = batch_size, num_steps

    def __iter__(self):
        return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps)


def load_data_time_machine(batch_size, num_steps,
                           use_random_iter=False, max_tokens=10000):
    """返回时光机器数据集的迭代器和词汇表。"""
    data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,
                              max_tokens)
    return data_iter, data_iter.vocab



# 初始化模型参数
def get_params(vocab_size, num_hiddens, device):
    # 输入等于输出等于字典大小
    num_inputs = num_outputs = vocab_size
    # 均值为0方差为1的随机张量*0.01
    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01
    # 输入到隐藏层边缘的W
    W_xh = normal((num_inputs, num_hiddens))
    # 隐藏层的W
    W_hh = normal((num_hiddens, num_hiddens))
    b_h = torch.zeros(num_hiddens, device=device)
    # 隐藏层到输出的W
    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

# 初始化隐藏状态
def init_rnn_state(batch_size, num_hiddens, device):
    # 批量大小,隐藏层大小的全0张量
    return (torch.zeros((batch_size, num_hiddens), device=device),)

# 计算输出
def rnn(inputs, state, params):
    W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state
    outputs = []
    for X in inputs:
        # 激活函数是tanh H为初始化隐藏状态
        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)
        # H为当前隐藏状态
    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)

# 推理测试
def predict_ch8(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])

# 梯度剪裁
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_ch8(net, train_iter, loss, updater, device, use_random_iter):
    """训练模型一个迭代周期(定义见第8章)。"""
    state = None
    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])


def train_ch8(net, train_iter, vocab, lr, num_epochs, device,
              use_random_iter=False):
    """训练模型(定义见第8章)。"""
    loss = nn.CrossEntropyLoss()

    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 = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
    for epoch in range(num_epochs):
        ppl = train_epoch_ch8(net, train_iter, loss, updater, device,
                                     use_random_iter)
        if (epoch + 1) % 10 == 0:
            print(predict('But'))

    print(f'困惑度 {ppl:.1f},  {str(device)}')
    print(predict('But'))


# 批量大小为32  时序序列的长度为35 隐藏层大小512
batch_size, num_steps, num_hiddens = 32, 35, 512
# 获取迭代数据和字典
train_iter, vocab = load_data_time_machine(batch_size, num_steps)
# 定义网络
net = RNNModelScratch(len(vocab), num_hiddens, torch.device('cpu'), get_params,
                      init_rnn_state, rnn)
# 训练500轮 学习率为1
num_epochs, lr = 50, 1
# 训练
train_ch8(net, train_iter, vocab, lr, num_epochs, torch.device('cpu'),
          use_random_iter=True)

训练结果

<unk>ut the the the the the the the the the the the the t
<unk>uthe the the the the the the the the the the the the
<unk>uthe sher and the sher and the sher and the sher and
<unk>uthe sher and the sher and the sher and the sher and
<unk>uthe sher and he her sher and her sher and her sher 
困惑度 8.8,  cpu
<unk>uthe sher and he her sher and her sher and her sher 

Process finished with exit code 0

文章来源:https://blog.csdn.net/qq_39879126/article/details/134927609
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。