动手学深度学习(Pytorch版)代码实践 -循环神经网络-53语言模型和数据集

53语言模型和数据集

1.自然语言统计

引入库和读取数据:

import random
import torch
from d2l import torch as d2l
import liliPytorch as lp
import numpy as np
import matplotlib.pyplot as plt

tokens = lp.tokenize(lp.read_time_machine())

一元语法:

# 一元语法
# 因为每个文本行不一定是一个句子或一个段落,因此我们把所有文本行拼接到一起
corpus = [token for line in tokens for token in line]
vocab = lp.Vocab(corpus)
# print(vocab.token_freqs[:5])
# [('the', 2261), ('i', 1267), ('and', 1245), ('of', 1155), ('a', 816)]
freqs = [freq for token, freq in vocab.token_freqs]
d2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)',
         xscale='log', yscale='log')
plt.show()

在这里插入图片描述

二元语法:

# 二元语法
bigram_tokens = [pair for pair in zip(corpus[:-1], corpus[1:])]
bigram_vocab = lp.Vocab(bigram_tokens)
# print(bigram_vocab.token_freqs[:5])
# [(('of', 'the'), 309), (('in', 'the'), 169), (('i', 'had'), 130),
# (('i', 'was'), 112), (('and', 'the'), 109)]
freqs = [freq for token, freq in bigram_vocab.token_freqs]
d2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)',
         xscale='log', yscale='log')
plt.show()

在这里插入图片描述

三元语法:

# 三元语法
trigram_tokens = [triple for triple in zip(corpus[:-2], corpus[1:-1], corpus[2:])]
trigram_vocab = lp.Vocab(trigram_tokens)
# print(trigram_vocab.token_freqs[:5])
# [(('the', 'time', 'traveller'), 59), (('the', 'time', 'machine'), 30), (('the', 'medical', 'man'), 24),
#  (('it', 'seemed', 'to'), 16), (('it', 'was', 'a'), 15)]
freqs = [freq for token, freq in trigram_vocab.token_freqs]
d2l.plot(freqs, xlabel='token: x', ylabel='frequency: n(x)',
         xscale='log', yscale='log')
plt.show()

在这里插入图片描述
对比:

# 一元语法、二元语法和三元语法对比
freqs = [freq for token, freq in vocab.token_freqs]
bigram_freqs = [freq for token, freq in bigram_vocab.token_freqs]
trigram_freqs = [freq for token, freq in trigram_vocab.token_freqs]
d2l.plot([freqs, bigram_freqs, trigram_freqs], xlabel='token: x',
         ylabel='frequency: n(x)', xscale='log', yscale='log',
         legend=['unigram', 'bigram', 'trigram'])
plt.show()

在这里插入图片描述

2.读取长序列数据
# n元语法,n 等于 num_steps
# 读取长序列数据
# 随机采样
def seq_data_iter_random(corpus, batch_size, num_steps):  #@save
    """使用随机抽样生成一个小批量子序列"""
    # 从随机偏移量开始对序列进行分区,随机范围包括num_steps-1
    # 从一个随机位置开始截取corpus,以生成一个新的子列表
    # random.randint(a, b) 会生成一个范围在 a 到 b 之间的整数,并且包括 a 和 b
    corpus = corpus[random.randint(0, num_steps - 1) : ]
    # 减去1,是因为我们需要考虑标签
    num_subseqs = (len(corpus) - 1) // num_steps
    # 长度为num_steps的子序列的起始索引
    initial_indices = list(range(0, num_subseqs * num_steps, num_steps))
    # 在随机抽样的迭代过程中,
    # 来自两个相邻的、随机的、小批量中的子序列不一定在原始序列上相邻
    random.shuffle(initial_indices)

    def data(pos):
        # 返回从pos位置开始的长度为num_steps的序列
        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包含子序列的随机起始索引
        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 np.array(X), np.array(Y)

my_seq = list(range(35))
# for X, Y in seq_data_iter_random(my_seq, batch_size=3, num_steps=5):
#     print('X: ', X, '\nY:', Y)
"""
X:  [[14 15 16 17 18]
 [19 20 21 22 23]
 [ 9 10 11 12 13]]
Y: [[15 16 17 18 19]
 [20 21 22 23 24]
 [10 11 12 13 14]]
X:  [[24 25 26 27 28]
 [29 30 31 32 33]
 [ 4  5  6  7  8]]
Y: [[25 26 27 28 29]
 [30 31 32 33 34]
 [ 5  6  7  8  9]]
"""

# 顺序分区
def seq_data_iter_sequential(corpus, batch_size, num_steps):  #@save
    """使用顺序分区生成一个小批量子序列"""
    # 从随机偏移量开始划分序列
    # random.randint(a, b) 会生成一个范围在 a 到 b 之间的整数,并且包括 a 和 b
    offset = random.randint(0, num_steps-1)
    # 根据偏移量和批量大小计算出可以使用的令牌数量,确保所有批次中的样本数量一致
    num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size
    Xs = np.array(corpus[offset: offset + num_tokens]) # 数组
    Ys = np.array(corpus[offset + 1: offset + 1 + num_tokens])
    Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1)
    # print(Xs)
    #  [[ 4  5  6  7  8  9 10 11 12 13 14 15 16 17 18]
    #   [19 20 21 22 23 24 25 26 27 28 29 30 31 32 33]]
    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

# for X, Y in seq_data_iter_sequential(my_seq, batch_size=2, num_steps=5):
#     print('X: ', X, '\nY:', Y)
"""
X:  [[ 4  5  6  7  8]
 [19 20 21 22 23]]
Y: [[ 5  6  7  8  9]
 [20 21 22 23 24]]
X:  [[ 9 10 11 12 13]
 [24 25 26 27 28]]
Y: [[10 11 12 13 14]
 [25 26 27 28 29]]
X:  [[14 15 16 17 18]
 [29 30 31 32 33]]
Y: [[15 16 17 18 19]
 [30 31 32 33 34]]
"""

# 将上面的两个采样函数包装到一个类中, 以便稍后可以将其用作数据迭代器。
class SeqDataLoader:  #@save
    """加载序列数据的迭代器"""
    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 = lp.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,  #@save
                           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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 14:08:03       4 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 14:08:03       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 14:08:03       4 阅读
  4. Python语言-面向对象

    2024-07-10 14:08:03       5 阅读

热门阅读

  1. 实现淘客返利系统中的用户登录与权限管理

    2024-07-10 14:08:03       6 阅读
  2. 【力扣】每日一题—第70题,爬楼梯

    2024-07-10 14:08:03       8 阅读
  3. mysql快速精通(一)DQL数据查询语言

    2024-07-10 14:08:03       9 阅读
  4. 408第二轮复习 数据结构 第七章查找

    2024-07-10 14:08:03       10 阅读
  5. Python中的迭代器与可迭代对象的概念及其关系

    2024-07-10 14:08:03       10 阅读
  6. 大数据面试题之Greenplum(2)

    2024-07-10 14:08:03       7 阅读
  7. 准备GPU H20机器k8s环境时用到的链接

    2024-07-10 14:08:03       8 阅读
  8. 数据库的优点和缺点分别是什么

    2024-07-10 14:08:03       10 阅读
  9. SQL语句分类

    2024-07-10 14:08:03       10 阅读