torchtext
仅供个人学习使用,参考总结了一些文档,在下面内容中会注释。
文章目录
前言
torchtext的学习,为后面的Pytorch-CNN以及Pytorch-LSTM模型搭建做准备
常见的数据预处理:
Load File:加载数据文件;
Tokenization:分词;
Create Vocabulary:创建字典;
Indexify:将词与索引进行映射;
Word Vectors:创建或加载词向量;
Padding or Fix Length:按长度对文本进行补齐或截取;
Dataset Splits:划分数据集(如将数据集划分为训练集、验证集、测试集);
Batching and Iterators:将数据集按固定大小划分成 Batch;
torchtext中主要的类的作用
使用 torchtext.data.Field 定义样本各个field的处理流程(分词、数据预处理等),创建Example时的预处理,batch时的一些处理操作;
使用 torchtext.data.Example 将 torchtext.data.Field 处理成一条example,表示一个样本(数据+标签);
使用 torchtext.data.Dataset 将 torchtext.data.Example 数据集类,处理成数据集,也可对数据集进行划分等工作,getitem返回 Example实例;
使用迭代器: torchtext.data.Iterators 将 torchtext.data.Dataset 按照 batch_size 组装成 Batch 供模型训练使用;
使用 torchtext.data.vocab 和 torchtext.data.Vectors 创建词典、词和索引的一一对应、下载或使用预训练的词向量等;
一、torchtext.data
1.torchtext.data.Field
代码如下(Field):
class torchtext.data.Field(
sequential=True, use_vocab=True, init_token=None, eos_token=None, fix_length=None,
dtype=torch.int64, preprocessing=None, postprocessing=None, lower=False, tokenize=None,
tokenizer_language='en', include_lengths=False, batch_first=False, pad_token='<pad>',
unk_token='<unk>', pad_first=False, truncate_first=False, stop_words=None, is_target=False
):
'''
定义一个数据类型以及用于转换为Tensor的指令。
Field 类对可以由张量表示的常见文本处理数据类型进行建模。
它包含一个Vocab对象,该对象定义了字段元素及其对应的数字表示形式的可能值的集合。
Field对象还保存与数据类型应该如何数字化有关的其他参数,例如 tokenization 方法和应生成的Tensor的类型。
如果数据集中的两个列之间共享一个 Field,那么就共享 vocabulary。
sequential – 是否是序列化数据,如果是False, 不需要指定 tokenize 默认值: True。
use_vocab – 是否使用Vocab object. 如果是False, field中的数据必须已经是数值类型. 默认值: True。
init_token – 每条数据的起始字符 如果没有初始令牌则None,默认值: None。
eos_token – 每条数据的结尾字符 默认值: None。(同上)
fix_length – 每条数据的固定长度,不够的用pad_token补全. 默认值: None 不固定。
dtype – Default: torch.dtype 类 表示这类数据的一批样例,默认:torch.long。
preprocessing – 在tokenizing之后和numericalizing之前使用的pipeline, 默认值: None。
postprocessing – numericalizing 之后,转化成 tensor 之前使用的pipline默认值: None。
lower – 是否把数据转化为小写 默认值: False。
tokenize – 分词函数,如果是spacy,则使用SpaCy tokenizer。如果一个非序列化函数作为参数传递,则该field将无法序列化 默认值: str.split。
tokenizer_language – 目前仅在SpaCy中支持各种语言。 默认值: 'en'.
include_lengths – 是否返回一个已经补全的最小batch的元组和一个包含每条数据长度的列表 . 默认值: False。
batch_first – 是否先 生成batch尺寸的Tensor。默认值:False。
pad_token – 用于补全的字符. 默认值: '<pad>'。
unk_token – 不存在词典里的字符. 默认值:'<unk>'。
pad_first – 是否补全第一个字符. 默认值: False
truncate_first – 在开始时填充序列。默认值:False。
stop_words – 要在preprocessing步骤中丢弃的tokens。默认值:False。
is_target – filed是否为目标变量。影响batch迭代,默认值:False。
'''
def build_vocab(*args, **kwargs)
'''
从一个或多个数据集中为此字段构造Vocab对象。
'''
def numericalize(arr, device=None)
'''
将使用此 Field 的一批样本转换为变量。
arr (List[List[str]], or tuple of (List[List[str]], List[int]))
– 如果self.include_lengths is True。tokenized和padded的examples列表,或tokenized和padded的 examples列表元组,以及每个example的长度列表
– if self.include_lengths=True, tuple of List of tokenized and padded examples and List of lengths of each example.
device (str or torch.device) – Default: None (for cpu).
'''
def pad(minibatch)
'''
填充到self.fix_length或者此batch的最大长度。
前缀self.init_token 后缀self.eos_token。
if self.include_lengths=True,返回 (the padded list, length list).
if self.include_lengths=False,返回 the padded list.
if self.sequential=False,没有 pad.
'''
def preprocess(x)
'''
处理单个样本
if sequential=True,tokenize the input.
if lower=True,小写化.
然后传入用户定义的 preprocessing.
'''
def process(batch, device=None)
'''
pad, numericalize, and postprocess a batch and create a tensor.
'''
build_vocab
内置的预训练词向量:
Field_instance.build_vocab(train, vectors=data.vocab.GloVe(name='6B', dim=300))
Field_instance.build_vocab(train, vectors="glove.6B.300d")
本地的预训练词向量:
vectors = Vectors(name='myvector/glove/glove.6B.200d.txt')
TEXT.build_vocab(train, vectors=vectors)
通过name参数可以指定预训练词向量文件所在的路径。
vectors = Vectors(name='glove.6B.200d.txt', cache='myvector/glove/')
# 指定Vector缺失值的初始化方式,没有命中的token的初始化方式
vectors.unk_init = init.uniform_
TEXT.build_vocab(train, vectors=vectors)
通过cache参数指定缓存目录。
处理部分流程顺序:tokenizing -> lower -> preprocessing -> numericalizing -> postprocessing -> turn-into-Tensor.
demo
dataset
0 Tourists can wear skirts or dresses in India.
0 They were talking about the pools at the Maria Lenk Aquatics Centre.
0 There is Blank Space in Taylor Swift 's bank account.
0 Congress will pass a comprehensive measure.
1 Turkey 's legal quest for return of relics beginning to bear fruit.
1 Two former Brazilian presidents on Tuesday admitted allegations of corruption.
1 Additional troops will be sent to Afghanistan.
1 China and Mexico have tremendous cooperation potential in the e_commerce sector.
1 Donald Trump met with Russians during his father 's 2016 presidential campaign.
1 Some 700,000 people have evacuated from Cuba 's northeastern coast.
...
code
# 分词函数
def content_tokenize(text):
return [item for item in str(text)]
# 创建content字段的Field
CONTENT = data.Field(sequential=True, tokenize=content_tokenize, batch_first=True)
# 创建label字段的Field
LABEL = data.Field(sequential=False, use_vocab=False)
# 为 CONTENT 字段创建词向量
CONTENT.build_vocab(data_set)
CONTENT.vocab.stoi 需要保存起来,供以后使用。
If sequential=True,那么需要定义 tokenize

本文详细介绍了torchtext库在数据预处理中的应用,包括Field的配置,如分词、创建词汇表、词向量加载,以及Example、Dataset、Iterator的使用。torchtext提供了一套完整的流程,从加载数据、分词、创建词汇表、数值化、填充到批量处理,为PyTorch模型训练做好准备。此外,还展示了如何使用预训练的GloVe词向量,并给出了中文分词的示例。
最低0.47元/天 解锁文章
988

被折叠的 条评论
为什么被折叠?



