动手学深度学习PyTorch版--Task2--文本预处理;语言模型;循环神经网络基础
一.文本预处理
文本是一类序列数据,一篇文章可以看作是字符或单词的序列,本节将介绍文本数据的常见预处理步骤,预处理通常包括四个步骤:
1.读入文本
2.分词
3.建立字典,将每个词映射到一个唯一的索引(index)
4.将文本从词的序列转换为索引的序列,方便输入模型
1.读入文本
import collections
import re
def read_time_machine():
# open 函数打开文本文件,创建文件对象f
with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
# f可迭代,for line in f一次读取一行
# 文件的每一行用strip函数 去掉前缀后缀的空白字符(即空格/换行符/制表符),并将所有大写字符转为小写字符
# 其中[^a-z]+ 表示 非小写英文字符组成的至少一个字符
lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
return lines
lines = read_time_machine()
print('# sentences %d' % len(lines)) # 打印文件行数
'''
sentences 3221
'''
2.分词
我们对每个句子进行分词,也就是将一个句子划分成若干个词(token),转换为一个词的序列。
# sentences是一个字符串列表,每个字符串是一个句子
# token-标志:
# 如果是 word,做单词间的分词,每句以空格划分
# 如果是 char,做字符间的分词,将sentences列表的每个字符串(句子)转化为列表
# 无论是以何种方式,返回的是二维列表,一维是sentences的长度,二维是句子分词后的单词/字符的长度
def tokenize(sentences, token='word'):
"""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]
'''
[['the', 'time', 'machine', 'by', 'h', 'g', 'wells', ''], ['']]
'''
3.建立字典
为了方便模型处理,我们需要将字符串转换为数字。因此我们需要先构建一个字典(vocabulary),将每个词映射到一个唯一的索引编号。
class Vocab(object):
# 参数介绍
# tokens: 为上一个分词函数的结果,二维列表
# min_freq-阈值:对出现次数小于该数值的词,忽略
# use_special_tokens: 是否要对使用特殊token
def __init__(self, tokens, min_freq=0, use_special_tokens=False):
# 统计词频
counter = count_corpus(tokens) # <key,value>: <词,词缀>
self.token_freqs = list(counter.items())
# 记录字典所需维护的token
self.idx_to_token = []
if use_special_tokens: # 如果该参数为真,引入4个pad,bos,eos,unk
# padding, begin of sentence, end of sentence, unknown
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>']
# 如果该词的词频大于阈值 并且 该词不在idx_to_token中出现过
# 就取语料库中的词和词频 添加到idx_to_token 中,
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() # 词到索引的映射 定义为字典
# enumerate枚举idx_to_token中的每个词和每个词的下标
# 将词和每个词的下标添加到 token_to_idx中
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) # 返回一个字典,记录每个词的出现次数
4.将词转为索引
使用字典,我们可以将原文本中的句子从单词序列转换为索引序列
for i in range(8, 10):
print('words:', tokens[i])
print('indices:', vocab[tokens[i]])
'''
words: ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him', '']
indices: [1, 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
words: ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
indices: [20, 21, 22, 23, 24, 16, 25, 26, 27, 28, 29, 30]
'''
5.用现有工具进行分词
我们前面介绍的分词方式非常简单,它至少有以下几个缺点:
标点符号通常可以提供语义信息,但是我们的方法直接将其丢弃了
类似“shouldn’t", “doesn’t"这样的词会被错误地处理
类似"Mr.”, "Dr."这样的词会被错误地处理
我们可以通过引入更复杂的规则来解决这些问题,但是事实上,有一些现有的工具可以很好地进行分词,我们在这里简单介绍其中的两个:spaCy和NLTK。
下面是一个简单的例子:
text = "Mr. Chen doesn't agree with my suggestion."
# <spaCy方法>
import spacy
nlp = spacy.load('en_core_web_sm') # 导入en的language
doc = nlp(text)
print([token.text for token in doc])
'''
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
'''
# <NLTK方法>
from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))
'''
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']
'''
二.语言模型
1.介绍
2.n元语法
3.语言模型数据集
读取数据集
with open('/home/kesci/input/jaychou_lyrics4703/jaychou_lyrics.txt') as f:
corpus_chars = f.read()
print(len(corpus_chars)) # 共6万多个字符
print(corpus_chars[: 40]) # 输出前40个字符
corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ') # 将换行回车 换成空格
corpus_chars = corpus_chars[: 10000] # 只保留前1万个字符 作为语料库
'''
63282
想要有直升机
想要和你飞到宇宙去
想要和你融化在一起
融化在宇宙里
我每天每天每
'''
建立字符索引
idx_to_char = list(set(corpus_chars)) # 去重,转为列表,得到索引到字符的映射
# 枚举idx_to_char中的每个字符char和下标i,构造一个字典
char_to_idx = {char: i for i, char in enumerate(idx_to_char)} # 字符到索引的映射
vocab_size = len(char_to_idx) # 记录字典的大小
print(vocab_size)
# 将语料库中的每个字符转化为索引,得到一个索引的序列
corpus_indices = [char_to_idx[char] for char in corpus_chars]
# 取出索引序列的前20个索引
sample = corpus_indices[: 20]
# 取sample中索引对应的字符,
print('chars:', ''.join([idx_to_char[idx] for idx in sample]))
print('indices:', sample)
'''
1027
chars: 想要有直升机 想要和你飞到宇宙去 想要和
indices: [1022, 648, 1025, 366, 208, 792, 199, 1022, 648, 641, 607, 625, 26, 155, 130, 5, 199, 1022, 648, 641]
'''
将前两个代码整个到函数中
定义函数load_data_jay_lyrics,在后续章节中直接调用。
def load_data_jay_lyrics():
with open('/home/kesci/input/jaychou_lyrics4703/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
时序数据的采样
随机采样
每次从数据里随机采样一个小批量。其中批量大小batch_size是每个小批量的样本数,num_steps是每个样本所包含的时间步数。 在随机采样中,每个样本是原始序列上任意截取的一段序列,相邻的两个随机小批量在原始序列上的位置不一定相毗邻。
如下图所示,若batch_size为2,取两次,时间步数为6
如 原数据为:[0, 1, 2, 3, 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]
划分为:
[ 0, 1, 2, 3, 4, 5] [ 6, 7, 8, 9, 10, 11] [12, 13, 14, 15, 16, 17] [18, 19, 20, 21, 22, 23]
import torch
import random
'''
参数介绍
corpus_indices 序列
batch_size 批量大小
num_steps 时间步数
device 是否使用GPU
'''
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
# 计算序列能划分成几个样本:
# 减1是因为对于长度为n的序列,X最多只有包含其中的前n-1个字符,最后一个字符给Y使用
num_examples = (len(corpus_indices) - 1) // num_steps # 下取整,得到不重叠情况下的样本个数
example_indices = [i * num_steps for i in range(num_examples)] # 记录每个样本的第一个字符在corpus_indices中的下标.如 0 6 12 18
random.shuffle(example_indices) # 随机采样
# 返回从i开始的长为num_steps的序列:
def _data(i):
# 如取得i为6,则返回【ghijkl】
return corpus_indices[i: i + num_steps]
# 是否使用GPU:
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的各个样本的首字符的下标
# batch_size=2
# 第一批次
# batch_indices = example_indices[0] = 0
# batch_indices = example_indices[1] = 6
# 第二批次
# batch_indices = example_indices[2] = 12
# batch_indices = example_indices[3] = 18
X = [_data(j) for j in batch_indices]
# 返回从0开始的长为6的序列 [0,1,2,3,4,5]
# 返回从6开始的长为6的序列 [6,7,8,9,10,11]
# 返回从12开始的长为6的序列 [12,13,14,15,16,17]
# 返回从18开始的长为6的序列 [18,19,20,21,22,23]
Y = [_data(j + 1) for j in batch_indices]
# 返回从1开始的长为6的序列 [1,2,3,4,5,6]
# 返回从7开始的长为6的序列 [7,8,9,10,11,12]
# 返回从13开始的长为6的序列 [13,14,15,16,17,18]
# 返回从19开始的长为6的序列 [19,20,21,22,23,24]
yield torch.tensor(X, device=device), torch.tensor(Y, device=device)
my_seq = list(range(30))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=6):
print('X: ', X, '\nY:', Y, '\n')
'''
X: tensor([[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]])
X: tensor([[ 0, 1, 2, 3, 4, 5],
[18, 19, 20, 21, 22, 23]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[19, 20, 21, 22, 23, 24]])
'''
相邻采样
在相邻采样中,相邻的两个随机小批量在原始序列上的位置相毗邻。
如下图所示,batch_size为2,每个颜色长度为6
如 原数据为:[0, 1, 2, 3, 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]
先划分为:
[[ 0, 1, 2, 3, 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]]
再划分为
[[ [ 0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14]],
[ [15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27] ]]
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)
# resize成(batch_size, )即(2,15)
indices = indices.view(batch_size, -1)
# batch_num = (15-1)/6 = 2
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
'''
# 当i = 0
i = 0
X = indices[0][0:6] = [0,1,2,3,4,5]
Y = indices[0][1:7] = [1,2,3,4,5,6]
X = indices[1][0:6] = [15,16,17,18,19,20]
Y = indices[1][1:7] = [16,17,18,19,20,21]
# 当i = 1
i = 6
X = indices[0][6:11] = [6,7,8,9,10,11]
Y = indices[0][7:12] = [7,8,9,10,11,12]
X = indices[1][6:11] = [21,22,23,24,25,26]
Y = indices[1][7:12] = [22,23,24,25,26,27]
'''
'''
corpus_indices:
[0, 1, 2, 3, 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]
indices:
tensor([[ 0, 1, 2, 3, 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]])
'''
同样的设置下,打印相邻采样每次读取的小批量样本的输入X和标签Y。相邻的两个随机小批量在原始序列上的位置相毗邻。
for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=6):
print('X: ', X, '\nY:', Y, '\n')
'''
X: tensor([[ 0, 1, 2, 3, 4, 5],
[15, 16, 17, 18, 19, 20]])
Y: tensor([[ 1, 2, 3, 4, 5, 6],
[16, 17, 18, 19, 20, 21]])
X: tensor([[ 6, 7, 8, 9, 10, 11],
[21, 22, 23, 24, 25, 26]])
Y: tensor([[ 7, 8, 9, 10, 11, 12],
[22, 23, 24, 25, 26, 27]])
'''
上一篇: Tensorflow 02: 卷积神经网络-MNIST
下一篇: 优化深度神经网络笔记(二)优化算法