• 文件 >
  • torchtext.transforms
捷徑

torchtext.transforms

轉換是常見的文字轉換。它們可以使用 torch.nn.Sequentialtorchtext.transforms.Sequential 鏈接在一起,以支援 torch-scriptability。

SentencePieceTokenizer

class torchtext.transforms.SentencePieceTokenizer(sp_model_path: str)[原始碼]

從預先訓練的 sentencepiece 模型進行 Sentence Piece 分詞器的轉換

更多細節:https://github.com/google/sentencepiece

參數:

sp_model_path (str) – 預先訓練的 sentencepiece 模型的路徑

範例
>>> from torchtext.transforms import SentencePieceTokenizer
>>> transform = SentencePieceTokenizer("spm_model")
>>> transform(["hello world", "attention is all you need!"])
使用 SentencePieceTokenizer 的教學
SST-2 Binary text classification with XLM-RoBERTa model

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類
forward(input: Any) Any[原始碼]
參數:

input (Union[str, List[str]]) – 要應用分詞器的輸入句子或句子列表。

回傳:

分詞後的文字

回傳型別:

Union[List[str], List[List[str]]]

GPT2BPETokenizer

class torchtext.transforms.GPT2BPETokenizer(encoder_json_path: str, vocab_bpe_path: str, return_tokens: bool = False)[原始碼]

GPT-2 BPE 分詞器的轉換。

在 TorchScript 中重新實作 openai GPT-2 BPE。原始 openai 實作:https://github.com/openai/gpt-2/blob/master/src/encoder.py

參數:
  • encoder_json_path (str) – GPT-2 BPE 編碼器 json 檔案的路徑。

  • vocab_bpe_path (str) – bpe 詞彙檔案的路徑。

  • return_tokens – 指示是否回傳分割的詞。如果為 False,它將回傳編碼的詞 ID 作為字串(預設值:False)

forward(input: Any) Any[原始碼]
參數:

input (Union[str, List[str]]) – 要應用分詞器的輸入句子或句子列表。

回傳:

分詞後的文字

回傳型別:

Union[List[str], List[List(str)]]

CLIPTokenizer

class torchtext.transforms.CLIPTokenizer(merges_path: str, encoder_json_path: Optional[str] = None, num_merges: Optional[int] = None, return_tokens: bool = False)[原始碼]

CLIP 分詞器的轉換。基於位元組級 BPE。

在 TorchScript 中重新實作 CLIP 分詞器。原始實作:https://github.com/mlfoundations/open_clip/blob/main/src/clip/tokenizer.py

這個分詞器已經過訓練,可以將空格視為詞的一部分(有點像 sentencepiece),因此一個詞在句子開頭(沒有空格)或不在句子開頭的編碼方式會有所不同。

以下程式碼片段顯示如何使用 CLIP 分詞器,以及從原始論文實作中取得的編碼器和合併檔案。

範例
>>> from torchtext.transforms import CLIPTokenizer
>>> MERGES_FILE = "http://download.pytorch.org/models/text/clip_merges.bpe"
>>> ENCODER_FILE = "http://download.pytorch.org/models/text/clip_encoder.json"
>>> tokenizer = CLIPTokenizer(merges_path=MERGES_FILE, encoder_json_path=ENCODER_FILE)
>>> tokenizer("the quick brown fox jumped over the lazy dog")
參數:
  • merges_path (str) – bpe 合併檔案的路徑。

  • encoder_json_path (str) – 可選,BPE 編碼器 json 檔案的路徑。如果指定,則用於推斷 num_merges。

  • num_merges (int) – 可選,要從 bpe 合併檔案讀取的合併次數。

  • return_tokens – 指示是否回傳分割的詞。如果為 False,它將回傳編碼的詞 ID 作為字串(預設值:False)

forward(input: Any) Any[原始碼]
參數:

input (Union[str, List[str]]) – 要應用分詞器的輸入句子或句子列表。

回傳:

分詞後的文字

回傳型別:

Union[List[str], List[List(str)]]

RegexTokenizer

class torchtext.transforms.RegexTokenizer(patterns_list)[原始碼]

適用於字串句子的 Regex tokenizer,它會套用 patterns_list 中定義的所有 regex 置換。它由 Google 的 C++ RE2 正規表示式引擎 支援。

參數:
  • patterns_list (List[Tuple[str, str]]) – 一個元組(有序對)清單,其中包含 regex 模式字串

  • element. (作為第一個元素,而替換字串作為第二個元素) –

注意事項
  • RE2 函式庫不支援任意的前瞻或後顧斷言,也不支援反向參考。請參閱此處的文件以取得更多資訊。

  • 最後的標記化步驟一律使用空格作為分隔符號。若要根據特定的 regex 模式分割字串,類似於 Python 的 re.split,可以提供一個 ('<regex_pattern>', ' ') 元組。

範例
基於 (patterns, replacements) 清單的 Regex 標記化。
>>> import torch
>>> from torchtext.transforms import RegexTokenizer
>>> test_sample = 'Basic Regex Tokenization for a Line of Text'
>>> patterns_list = [
    (r''', ' '  '),
    (r'"', '')]
>>> reg_tokenizer = RegexTokenizer(patterns_list)
>>> jit_reg_tokenizer = torch.jit.script(reg_tokenizer)
>>> tokens = jit_reg_tokenizer(test_sample)
基於 (single_pattern, ' ') 清單的 Regex 標記化。
>>> import torch
>>> from torchtext.transforms import RegexTokenizer
>>> test_sample = 'Basic.Regex,Tokenization_for+a..Line,,of  Text'
>>> patterns_list = [
    (r'[,._+ ]+', r' ')]
>>> reg_tokenizer = RegexTokenizer(patterns_list)
>>> jit_reg_tokenizer = torch.jit.script(reg_tokenizer)
>>> tokens = jit_reg_tokenizer(test_sample)
forward(line: str) List[str][原始碼]
參數:

lines (str) – 要標記化的文字字串。

回傳:

regex 後的標記清單。

回傳型別:

List[str]

BERTTokenizer

類別 torchtext.transforms.BERTTokenizer(vocab_path: str, do_lower_case: bool = True, strip_accents: Optional[bool] = None, return_tokens=False, never_split: Optional[List[str]] = None)[原始碼]

BERT Tokenizer 的轉換。

基於論文中介紹的 WordPiece 演算法:https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf

後端核心實作取自 https://github.com/LieluoboAi/radish 並進行修改。

如需更多詳細資訊,請參閱 PR https://github.com/pytorch/text/pull/1707 摘要。

以下程式碼片段顯示如何使用預先訓練的詞彙檔案使用 BERT tokenizer。

範例
>>> from torchtext.transforms import BERTTokenizer
>>> VOCAB_FILE = "https://huggingface.tw/bert-base-uncased/resolve/main/vocab.txt"
>>> tokenizer = BERTTokenizer(vocab_path=VOCAB_FILE, do_lower_case=True, return_tokens=True)
>>> tokenizer("Hello World, How are you!") # single sentence input
>>> tokenizer(["Hello World","How are you!"]) # batch input
參數:
  • vocab_path (str) – 預先訓練的詞彙檔案路徑。該路徑可以是本機路徑或 URL。

  • do_lower_case (Optional[bool]) – 指示是否轉換為小寫。(預設值:True)

  • strip_accents (Optional[bool]) – 指示是否移除重音。(預設值:None)

  • return_tokens (bool) – 指示是否傳回標記。如果為 false,則傳回對應的標記 ID 作為字串(預設值:False)

  • never_split (Optional[List[str]]) – 不會在標記化期間分割的標記集合。(預設值:None)

forward(input: Any) Any[原始碼]
參數:

input (Union[str, List[str]]) – 要應用分詞器的輸入句子或句子列表。

回傳:

分詞後的文字

回傳型別:

Union[List[str], List[List(str)]]

VocabTransform

類別 torchtext.transforms.VocabTransform(vocab: Vocab)[原始碼]

Vocab 轉換,用於將輸入的標記批次轉換為對應的標記 ID

參數:

vocabtorchtext.vocab.Vocab 類別的實例。

範例

>>> import torch
>>> from torchtext.vocab import vocab
>>> from torchtext.transforms import VocabTransform
>>> from collections import OrderedDict
>>> vocab_obj = vocab(OrderedDict([('a', 1), ('b', 1), ('c', 1)]))
>>> vocab_transform = VocabTransform(vocab_obj)
>>> output = vocab_transform([['a','b'],['a','b','c']])
>>> jit_vocab_transform = torch.jit.script(vocab_transform)
使用 VocabTransform 的教學
SST-2 Binary text classification with XLM-RoBERTa model

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類
forward(input: Any) Any[原始碼]
參數:

input (Union[List[str], List[List[str]]]) – 要轉換為對應標記 ID 的輸入標記批次

回傳:

已將輸入轉換為對應的標記 ID

回傳型別:

Union[List[int], List[List[int]]]

ToTensor

類別 torchtext.transforms.ToTensor(padding_value: Optional[int] = None, dtype: dtype = torch.int64)[原始碼]

將輸入轉換為 torch 張量

參數:
  • padding_value (Optional[int]) – 填補值,用於使批次中每個輸入的長度等於批次中最長序列的長度。

  • dtype (torch.dtype) – 輸出張量的 torch.dtype

forward(input: Any) Tensor[原始碼]
參數:

input (Union[List[int], List[List[int]]]) – 標記 ID 的序列或批次

回傳型別:

張量

LabelToIndex

class torchtext.transforms.LabelToIndex(label_names: Optional[List[str]] = None, label_path: Optional[str] = None, sort_names=False)[原始碼]

將標籤從字串名稱轉換為 ID。

參數:
  • label_names (Optional[List[str]]) – 唯一標籤名稱的清單

  • label_path (Optional[str]) – 包含唯一標籤名稱的檔案路徑,每行包含 1 個標籤。請注意,應提供 label_names 或 label_path,但不能同時提供。

forward(input: Any) Any[原始碼]
參數:

input (Union[str, List[str]]) – 要轉換為相應 ID 的輸入標籤

回傳型別:

Union[int, List[int]]

Truncate

class torchtext.transforms.Truncate(max_seq_len: int)[原始碼]

截斷輸入序列

參數:

max_seq_len (int) – 輸入序列允許的最大長度

使用 Truncate 的教學
SST-2 Binary text classification with XLM-RoBERTa model

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類
forward(input: Any) Any[原始碼]
參數:

input (Union[List[Union[str, int]], List[List[Union[str, int]]]]) – 要截斷的輸入序列或序列批次

回傳:

截斷的序列

回傳型別:

Union[List[Union[str, int]], List[List[Union[str, int]]]]

AddToken

class torchtext.transforms.AddToken(token: Union[int, str], begin: bool = True)[原始碼]

將權杖新增到序列的開頭或結尾

參數:
  • token (Union[int, str]) – 要新增的權杖

  • begin (bool, optional) – 是否在序列的開頭或結尾插入權杖,預設為 True

使用 AddToken 的教學
SST-2 Binary text classification with XLM-RoBERTa model

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類
forward(input: Any) Any[原始碼]
參數:

input (Union[List[Union[str, int]], List[List[Union[str, int]]]]) – 輸入序列或批次

Sequential

class torchtext.transforms.Sequential(*args: Module)[原始碼]
class torchtext.transforms.Sequential(arg: OrderedDict[str, Module])

用於存放一系列文字轉換的容器。

使用 Sequential 的教學
SST-2 Binary text classification with XLM-RoBERTa model

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類

使用 XLM-RoBERTa 模型進行 SST-2 二元文本分類
forward(input: Any) Any[原始碼]
參數:

input (Any) – 輸入序列或批次。輸入類型必須由序列中的第一個轉換支援。

PadTransform

class torchtext.transforms.PadTransform(max_length: int, pad_value: int)[原始碼]

使用給定的填補值將張量填補到固定長度。

參數:
  • max_length (int) – 要填充的最大長度

  • pad_value (bool) – 用於填充張量的值

forward(x: Tensor) Tensor[原始碼]
參數:

x (Tensor) – 要填充的張量

回傳:

使用 pad_value 填充到 max_length 的張量

回傳型別:

張量

StrToIntTransform

class torchtext.transforms.StrToIntTransform[原始碼]

將字串權杖轉換為整數(單一序列或批次)。

forward(input: Any) Any[原始碼]
參數:

input (Union[List[str], List[List[str]]]) – 要轉換的字串權杖序列或批次

回傳:

轉換為相應權杖 ID 的序列或批次

回傳型別:

Union[List[int], List[List[int]]]

CharBPETokenizer

class torchtext.transforms.CharBPETokenizer(bpe_encoder_path: str, bpe_merges_path: str, return_tokens: bool = False, unk_token: Optional[str] = None, suffix: Optional[str] = None, special_tokens: Optional[List[str]] = None)[原始碼]

用於字元位元組對編碼標記器的轉換。

:param : param bpe_encoder_path: BPE 編碼器 json 檔案的路徑。 :param : type bpe_encoder_path: str :param : param bpe_merges_path: BPE 合併文字檔案的路徑。 :param : type bpe_merges_path: str :param : param return_tokens: 指示是否返回分割後的權杖。 如果為 False,則返回編碼後的權杖 ID(預設值:False)。 :param : type return_tokens: bool :param : param unk_token: 未知權杖。 如果提供,則它必須存在於編碼器中。 :param : type unk_token: Optional[str] :param : param suffix: 用於每個作為詞尾的子詞的後綴。 :param : type suffix: Optional[str] :param : param special_tokens: 不應分割成單獨字元的特殊權杖。 如果提供,則這些權杖必須存在於編碼器中。 :param : type special_tokens: Optional[List[str]]

forward(input: Union[str, List[str]]) Union[List, List[List]][原始碼]

模組的正向方法將字串或字串清單編碼為權杖 ID

參數:

input – 要應用標記器的輸入句子或句子清單。

回傳:

權杖 ID 的清單或清單清單

文件

取得 PyTorch 的完整開發人員文件

檢視文件

教學

取得針對初學者和進階開發人員的深入教學

檢視教學

資源

尋找開發資源並獲得問題解答

檢視資源