循环神经网络的数据集处理
·
本文以time Machine数据集为例,使用mxnet框架。

引入库
import collections
import re
from d2l import mxnet as d2l
读取数据集
使用read_time_machine函数,不区分大小写(全部转化为小写),去除标点符号,将每一行取出使用列表生成器构成列表,每个元素为一行
#@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])
输出结果:
# 文本总行数: 3221 the time machine by h g wells twinkled and his usually pale face was flushed and animated the
词元化
tokenize()函数做分割,此处token的值用于区别line是字符串形式分割还是字符形式分割。
默认以字符串(单词)分割。
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']
构建词表
基本说明
- tokens为输入数组,min_freq表示保留的最小频率,默认为0,即保留所有出现的词元,reserved_tokens为默认保留的词元。
- collection.Counter()为python标准类库的方法,其返回值为一个字典,每个元素由内容和出现频率构成。
- idx_to_token为数组,第一个元素为未知词元,其容纳所有词元,数组索引为其索引。
- token_to_id为字典,第一个元素为未知词元及其对应数量,其格式为(词元,频率)。
- for-each-loop遍历所有词元,将其添加到idx_to_token和token_to_idx中。
其他函数说明
__getitem__为根据词元找出id的方法,调用for-each loop,当传入为列表或元组(即多个词元)时,将其内部每个词元分割获得id,传入为单个词元时,转化词元为id。
注意:存储的id不是词元出现的频率
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)
看一下token_to_id(也就是存储的字典)的输出,发现存储的id确实是在数组中的位置(序号)。
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)]
功能优化说明
我们已经注意到,在之前的实现中,除了对word进行分割之外,还有对char进行分割,做法上没有太大区别。在使用中文语料库中,可以直接使用字来进行分割,我们在英语中常常采取按char类型词元化和构建词表。
整合所有功能
我们将所有功能集中打包到load_corpus_time_machine()中,并对其进行测试。
需要注意的是,corpus为语料库,machine learning总词数为30000左右,vocab是词表内容数。
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)
输出结果如下:(十七万为总字母数,28为26个字母加上添加的其他词元)
(170580, 28)
思考
1.vocab词表为28,究竟出现的是哪些词元呢?
2.为什么采用char类型来分割呢?
更多推荐
所有评论(0)