循环神经网络——上篇【深度学习】【PyTorch】【d2l】

6、循环神经网络

6.1、序列模型

6.1.1、序列模型

序列模型主要用于处理具有时序结构的数据, **时序数据是连续的,**随着时间的推移,如电影评分、电影奖项、电影导演演员等。

p ( x ) = p ( x 1 ) ⋅ p ( x 2 ∣ x 1 ) ⋅ p ( x 3 ∣ x 2 , x 1 ) ⋅ . . . ⋅ p ( x T ∣ x 1 , x 2 , . . . , x T − 1 ) p(x)=p(x_1)·p(x_2|x_1)·p(x_3|x_2,x_1)·...·p(x_T|x_1,x_2,...,x_{T-1}) p(x)=p(x1)p(x2x1)p(x3x2,x1)...p(xTx1,x2,...,xT1)

反序推测

p ( x ) = p ( x T ) ⋅ p ( x T − 1 ∣ x T ) ⋅ p ( x T − 2 ∣ x T − 1 , x T ) ⋅ . . . ⋅ p ( x 1 ∣ x 2 , x 2 , . . . , x T ) p(x)=p(x_T)·p(x_{T-1}|x_{T})·p(x_{T-2}|x_{T-1},x_{T})·...·p(x_1|x_2,x_2,...,x_{T}) p(x)=p(xT)p(xT1xT)p(xT2xT1,xT)...p(x1x2,x2,...,xT)

从未来去推前面发生什么,物理上不一定可行。

6.1.2、条件概率建模

公式

p ( x t ∣ x 1 , . . . , x t − 1 ) = p ( x t ∣ f ( x 1 , . . . , x t − 1 ) ) p(x_t|x_1,...,x_{t-1}) = p(x_t|f(x_1,...,x_{t-1})) p(xtx1,...,xt1)=p(xtf(x1,...,xt1))

对过去的数据建模,使用自身过去数据去预测自身未来数据,称为自回归模型。

建模方案

1)马尔科夫假设

相当长的序列 x t − 1 , . . . , x 2 , x 1 x_{t-1},...,x_2,x_1 xt1,...,x2,x1是不必要的,满足 τ τ τ长度的序列 x t − τ , x t − τ − 1 . . . , x t − 1 x_{t-τ},x_{t-τ-1}...,x_{t-1} xtτ,xtτ1...,xt1足够。

2)潜变量模型

引入潜变量 h t h_t ht表示过去的信息。

在这里插入图片描述

h t = f ( x 1 , . . . , x t − 1 ) h_t = f(x_1,...,x_{t-1}) ht=f(x1,...,xt1)

p ( x t ∣ x 1 , . . . , x t − 1 ) = p ( x t ∣ f ( x 1 , . . . , x t − 1 ) ) p(x_t|x_1,...,x_{t-1}) = p(x_t|f(x_1,...,x_{t-1})) p(xtx1,...,xt1)=p(xtf(x1,...,xt1))

因此,

x t = p ( x t ∣ h t ) x_t =p(x_t|h_t) xt=p(xtht)

6.1.2、代码实现

生成类似正弦变换的样本数据

%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l

T = 1000  # 总共产生1000个点
time = torch.arange(1, T + 1, dtype=torch.float32)
x = torch.sin(0.01 * time) + torch.normal(0, 0.2, (T,))
d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3))

在这里插入图片描述

将这个序列转换为模型的特征-标签对(feature-label)

若没有足够的历史记录来描述前τ个数据样本。 一个简单的解决办法是:如果拥有足够长的序列就丢弃这几项; 另一个方法是用零填充序列。

tau = 4
features = torch.zeros((T - tau, tau))
for i in range(tau):
    features[:, i] = x[i: T - tau + i]
labels = x[tau:].reshape((-1, 1))

batch_size, n_train = 16, 600
# 只有前n_train个样本用于训练
train_iter = d2l.load_array((features[:n_train], labels[:n_train]),
                            batch_size, is_train=True)

定义模型

# 初始化网络权重的函数
def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.xavier_uniform_(m.weight)

# 一个简单的多层感知机
def get_net():
    net = nn.Sequential(nn.Linear(4, 10),
                        nn.ReLU(),
                        nn.Linear(10, 1))
    net.apply(init_weights)
    return net

# 平方损失。注意:MSELoss计算平方误差时不带系数1/2
loss = nn.MSELoss(reduction='none')

训练

def train(net, train_iter, loss, epochs, lr):
    trainer = torch.optim.Adam(net.parameters(), lr)
    for epoch in range(epochs):
        for X, y in train_iter:
            trainer.zero_grad()
            l = loss(net(X), y)
            l.sum().backward()
            trainer.step()
        print(f'epoch {epoch + 1}, '
              f'loss: {d2l.evaluate_loss(net, train_iter, loss):f}')

net = get_net()
train(net, train_iter, loss, 5, 0.01)
epoch 1, loss: 0.063649
epoch 2, loss: 0.060103
epoch 3, loss: 0.056767
epoch 4, loss: 0.056202
epoch 5, loss: 0.054945

预测

onestep_preds = net(features)
d2l.plot([time, time[tau:]],
         [x.detach().numpy(), onestep_preds.detach().numpy()], 'time',
         'x', legend=['data', '1-step preds'], xlim=[1, 1000],
         figsize=(6, 3))

在这里插入图片描述

6.2、文本预处理

6.2.1、理论部分

解析文本|预处理步骤:

  1. 将文本作为字符串加载到内存中;
  2. 将字符串拆分为词元(如单词和字符);
  3. 建立一个词表,将拆分的词元映射到数字索引;
  4. 将文本转换为数字索引序列,方便模型操作。

6.2.2、代码实现

import collections
import re
from d2l import torch as d2l

步骤一:读取数据集

这里为了简化,忽略了标点符号和字母大写。

#@save
d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',
                                '090b5e7e70c295757f55df93cb0a180b9691891a')

def read_time_machine():  #@save
    """将时间机器数据集加载到文本行的列表中"""
    with open(d2l.download('time_machine'), 'r') as f:
        lines = f.readlines()
    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]

lines = read_time_machine()
print(f'# 文本总行数: {len(lines)}')
print(lines[0])
print(lines[10])
Downloading ..\data\timemachine.txt from http://d2l-data.s3-accelerate.amazonaws.com/timemachine.txt...
# 文本总行数: 3221
the time machine by h g wells
twinkled and his usually pale face was flushed and animated the

步骤二:拆分词元

def tokenize(lines, token='word'):  #@save
    """将文本行拆分为单词或字符词元"""
    if token == 'word':
        return [line.split() for line in lines]
    elif token == 'char':
        return [list(line) for line in lines]
    else:
        print('错误:未知词元类型:' + token)

tokens = tokenize(lines)
for i in range(11):
    print(tokens[i])
['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
[]
[]
[]
[]
['i']
[]
[]
['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']
['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']

步骤三&四:建立词表&转换为数字序列

class Vocab:  #@save
    """文本词表"""
    def __init__(self, tokens=None, min_freq=0, reserved_tokens=None):
        if tokens is None:
            tokens = []
        if reserved_tokens is None:
            reserved_tokens = []
        # 按出现频率排序
        counter = count_corpus(tokens)
        self._token_freqs = sorted(counter.items(), key=lambda x: x[1],
                                   reverse=True)
        # 未知词元的索引为0
        self.idx_to_token = ['<unk>'] + reserved_tokens
        self.token_to_idx = {token: idx
                             for idx, token in enumerate(self.idx_to_token)}
        for token, freq in self._token_freqs:
            if freq < min_freq:
                break
            if token not in self.token_to_idx:
                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]

    @property
    def unk(self):  # 未知词元的索引为0
        return 0

    @property
    def token_freqs(self):
        return self._token_freqs

def count_corpus(tokens):  #@save
    """统计词元的频率"""
    # 这里的tokens是1D列表或2D列表
    if len(tokens) == 0 or isinstance(tokens[0], list):
        # 将词元列表展平成一个列表
        tokens = [token for line in tokens for token in line]
    return collections.Counter(tokens)

打印前10高频词及其索引

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[:10])
[('<unk>', 0), ('the', 1), ('i', 2), ('and', 3), ('of', 4), ('a', 5), ('to', 6), ('was', 7), ('in', 8), ('that', 9)]

将每行转换成一个数字索引列表(前10个词元列表)

for i in [0, 10]:
 print('文本:', tokens[i])
 print('索引:', vocab[tokens[i]])

功能整合

为了简化,使用字符(而不是单词)实现文本词元化;

时光机器数据集中的每个文本行不一定是一个句子或一个段落,还可能是一个单词,因此返回的corpus仅处理为单个列表,而不是使用多词元列表构成的一个列表。

def load_corpus_time_machine(max_tokens=-1):  #@save
    """返回时光机器数据集的词元索引列表和词表"""
    lines = read_time_machine()
    tokens = tokenize(lines, 'char')
    vocab = Vocab(tokens)
    # 因为时光机器数据集中的每个文本行不一定是一个句子或一个段落,
    # 所以将所有文本行展平到一个列表中
    corpus = [vocab[token] for line in tokens for token in line]
    if max_tokens > 0:
        corpus = corpus[:max_tokens]
    return corpus, vocab

corpus, vocab = load_corpus_time_machine()
len(corpus), len(vocab)
(170580, 28)

6.3、语言模型和数据集

(待补充)

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来杯Sherry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值