隨著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}},
}