随着Pytorch工具链的成熟,是时候像这样归档存储库了。您将能够找到此工具包的每个部分的更多开发选项:
开发快乐!
如果有人想不构建此回购并继续开发它,请随时与我联系。您可以通过“ petrochukm [at] gmail.com”与我联系。

pytorch-nlp或用于简称的torchnlp ,是Pytorch NLP的基本实用程序库。 torchnlp扩展了Pytorch,为您提供基本的文本数据处理功能。
Chloe Yeo徽标,Wellsaid Labs公司赞助
确保您的Python 3.6+和Pytorch 1.0+。然后,您可以使用PIP安装pytorch-nlp :
pip install pytorch - nlp或通过以下方式安装最新代码:
pip install git + https : // github . com / PetrochukM / PyTorch - NLP . git Pytorch-NLP的完整文档可通过我们的ReadThedocs网站获得。
在NLP数据管道中,您需要实现以下基本步骤:
加载IMDB数据集,例如:
from torchnlp . datasets import imdb_dataset
# Load the imdb training dataset
train = imdb_dataset ( train = True )
train [ 0 ] # RETURNS: {'text': 'For a movie that gets..', 'sentiment': 'pos'}加载自定义数据集,例如:
from pathlib import Path
from torchnlp . download import download_file_maybe_extract
directory_path = Path ( 'data/' )
train_file_path = Path ( 'trees/train.txt' )
download_file_maybe_extract (
url = 'http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip' ,
directory = directory_path ,
check_files = [ train_file_path ])
open ( directory_path / train_file_path )不用担心,我们会为您处理缓存!
令牌化并将文本编码为张量。
例如,每当遇到一个空格字符时, WhitespaceEncoder都会将文本分解为令牌。
from torchnlp . encoders . text import WhitespaceEncoder
loaded_data = [ "now this ain't funny" , "so don't you dare laugh" ]
encoder = WhitespaceEncoder ( loaded_data )
encoded_data = [ encoder . encode ( example ) for example in loaded_data ]掌握了加载和编码的数据,您需要批量数据集。
import torch
from torchnlp . samplers import BucketBatchSampler
from torchnlp . utils import collate_tensors
from torchnlp . encoders . text import stack_and_pad_tensors
encoded_data = [ torch . randn ( 2 ), torch . randn ( 3 ), torch . randn ( 4 ), torch . randn ( 5 )]
train_sampler = torch . utils . data . sampler . SequentialSampler ( encoded_data )
train_batch_sampler = BucketBatchSampler (
train_sampler , batch_size = 2 , drop_last = False , sort_key = lambda i : encoded_data [ i ]. shape [ 0 ])
batches = [[ encoded_data [ i ] for i in batch ] for batch in train_batch_sampler ]
batches = [ collate_tensors ( batch , stack_tensors = stack_and_pad_tensors ) for batch in batches ] Pytorch-NLP在Pytorch现有的torch.utils.data.sampler , torch.stack和default_collate e上构建,以支持长度不同的顺序输入!
借助批次,您可以使用Pytorch使用梯度下降来开发和训练模型。例如,查看此示例代码,以培训斯坦福大学自然语言推断(SNLI)语料库。
Pytorch-NLP还有更多专注于NLP的实用程序软件包,以支持您! ?
现在,您已经设置了管道,您可能需要确保某些功能确定运行。用fork_rng包装任何随机的代码,您会很好,就像这样:
import random
import numpy
import torch
from torchnlp . random import fork_rng
with fork_rng ( seed = 123 ): # Ensure determinism
print ( 'Random:' , random . randint ( 1 , 2 ** 31 ))
print ( 'Numpy:' , numpy . random . randint ( 1 , 2 ** 31 ))
print ( 'Torch:' , int ( torch . randint ( 1 , 2 ** 31 , ( 1 ,))))这将始终打印:
Random: 224899943
Numpy: 843828735
Torch: 843828736
现在您已经计算出词汇,您可能需要使用预训练的单词向量来设置嵌入,例如:
import torch
from torchnlp . encoders . text import WhitespaceEncoder
from torchnlp . word_to_vector import GloVe
encoder = WhitespaceEncoder ([ "now this ain't funny" , "so don't you dare laugh" ])
vocab_set = set ( encoder . vocab )
pretrained_embedding = GloVe ( name = '6B' , dim = 100 , is_include = lambda w : w in vocab_set )
embedding_weights = torch . Tensor ( encoder . vocab_size , pretrained_embedding . dim )
for i , token in enumerate ( encoder . vocab ):
embedding_weights [ i ] = pretrained_embedding [ token ]例如,从神经网络软件包中,应用最新的LockedDropout :
import torch
from torchnlp . nn import LockedDropout
input_ = torch . randn ( 6 , 3 , 10 )
dropout = LockedDropout ( 0.5 )
# Apply a LockedDropout to `input_`
dropout ( input_ ) # RETURNS: torch.FloatTensor (6x3x10)计算常见的NLP指标,例如BLEU评分。
from torchnlp . metrics import get_moses_multi_bleu
hypotheses = [ "The brown fox jumps over the dog 笑" ]
references = [ "The quick brown fox jumps over the lazy dog 笑" ]
# Compute BLEU score with the official BLEU perl script
get_moses_multi_bleu ( hypotheses , references , lowercase = True ) # RETURNS: 47.9也许查看较长的示例可能会对您有帮助examples/
需要更多帮助吗?我们很高兴通过吉特聊天回答您的问题
我们发布了Pytorch-NLP,因为我们发现Pytorch中NLP缺乏基本工具包。我们希望其他组织可以从该项目中受益。我们感谢社区的任何贡献。
阅读我们的贡献指南,以了解我们的开发过程,如何提出错误的文件和改进以及如何构建和测试您对Pytorch-NLP的更改。
TorchText和Pytorch-NLP在体系结构和功能集上有所不同。否则,它们是相似的。 TorchText和Pytorch-NLP提供了预训练的单词向量,数据集,迭代器和文本编码器。 Pytorch-NLP还提供神经网络模块和指标。从体系结构的角度来看,torchtext是针对对象的外部耦合,而pytorch-nlp则以低耦合为目标。
Allennlp旨在成为研究平台。 Pytorch-NLP设计为轻量级工具包。
如果您发现Pytorch-NLP对学术出版物有用,请使用以下Bibtex引用:
@misc{pytorch-nlp,
author = {Petrochuk, Michael},
title = {PyTorch-NLP: Rapid Prototyping with PyTorch Natural Language Processing (NLP) Tools},
year = {2018},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {url{https://github.com/PetrochukM/PyTorch-NLP}},
}