# torchtext.transforms > 原文:[`pytorch.org/text/stable/transforms.html`](https://pytorch.org/text/stable/transforms.html) 转换是常见的文本转换。它们可以使用[`torch.nn.Sequential`](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential)链接在一起,或者使用`torchtext.transforms.Sequential`来支持 torch-scriptability。 ## SentencePieceTokenizer ```py class torchtext.transforms.SentencePieceTokenizer(sp_model_path: str) ``` 从预训练 sentencepiece 模型转换为 Sentence Piece 标记器 附加细节:[`github.com/google/sentencepiece`](https://github.com/google/sentencepiece) 参数: **sp_model_path**([*str*](https://docs.python.org/3/library/stdtypes.html#str)) - 预训练 sentencepiece 模型的路径 示例 ```py >>> from torchtext.transforms import SentencePieceTokenizer >>> transform = SentencePieceTokenizer("spm_model") >>> transform(["hello world", "attention is all you need!"]) ``` 使用`SentencePieceTokenizer`的教程: ![SST-2 二进制文本分类与 XLM-RoBERTa 模型](img/98241cb68ab73fa3d56bc87944e16fd8.png) SST-2 二进制文本分类与 XLM-RoBERTa 模型 SST-2 二进制文本分类与 XLM-RoBERTa 模型 ```py forward(input: Any) → Any ``` 参数: **input**(*Union*[[*str*](https://docs.python.org/3/library/stdtypes.html#str), *List*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)]]) - 要应用标记器的输入句子或句子列表。 返回: 标记化文本 返回类型: Union[List[str], List[List[str]]] ## GPT2BPETokenizer ```py 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 实现[`github.com/openai/gpt-2/blob/master/src/encoder.py`](https://github.com/openai/gpt-2/blob/master/src/encoder.py) 参数: + **encoder_json_path**([*str*](https://docs.python.org/3/library/stdtypes.html#str)) - GPT-2 BPE 编码器 json 文件的路径。 + **vocab_bpe_path**([*str*](https://docs.python.org/3/library/stdtypes.html#str)) - bpe 词汇文件的路径。 + **return_tokens** - 指示是否返回拆分的标记。如果为 False,则将返回编码的标记 ID 作为字符串(默认值:False) ```py forward(input: Any) → Any ``` 参数: **input**(*Union*[[*str*](https://docs.python.org/3/library/stdtypes.html#str), *List*[*[*str*](https://docs.python.org/3/library/stdtypes.html#str)]]) - 要应用标记器的输入句子或句子列表。 返回: 标记化文本 返回类型: Union[List[str], List[List[str]]] ## CLIPTokenizer ```py class torchtext.transforms.CLIPTokenizer(merges_path: str, encoder_json_path: Optional[str] = None, num_merges: Optional[int] = None, return_tokens: bool = False) ``` 用于 CLIP Tokenizer 的转换。基于字节级 BPE。 在 TorchScript 中重新实现 CLIP Tokenizer。原始实现:[`github.com/mlfoundations/open_clip/blob/main/src/clip/tokenizer.py`](https://github.com/mlfoundations/open_clip/blob/main/src/clip/tokenizer.py) 这个标记器已经训练成将空格视为标记的一部分(有点像 sentencepiece),因此一个单词将根据它是否在句子开头(没有空格)而被编码为不同的方式。 下面的代码片段显示了如何使用来自原始论文实现的编码器和合并文件的 CLIP 标记器。 示例 ```py >>> 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*](https://docs.python.org/3/library/stdtypes.html#str)) - bpe 合并文件的路径。 + **encoder_json_path**([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"))- 可选,BPE 编码器 json 文件的路径。当指定时,用于推断 num_merges。 + **num_merges**([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)"))- 可选,从 bpe 合并文件中读取的合并次数。 + **return_tokens** - 指示是否返回拆分的标记。如果为 False,它将返回编码的标记 ID 作为字符串(默认值:False) ```py forward(input: Any) → Any ``` 参数: **input**(*Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* *List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]**]*)- 要应用分词器的输入句子或句子列表。 返回: 标记化文本 返回类型: Union[List[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")], List[List([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"))]] ## 正则表达式分词器 ```py class torchtext.transforms.RegexTokenizer(patterns_list) ``` 基于 patterns_list 中定义的所有正则表达式替换的字符串句子的正则表达式分词器。它由 Google 的[C++ RE2 正则表达式引擎](https://github.com/google/re2)支持。 参数: + **patterns_list**(*List**[**Tuple**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]**]*)- 包含正则表达式模式字符串的元组(有序对)列表 + **element.**(作为第一个元素和替换字符串作为第二个)- 注意事项 + RE2 库不支持任意的前瞻或后顾断言,也不支持反向引用。查看这里的[文档](https://swtch.com/~rsc/regexp/regexp3.html#caveats)以获取更多信息。 + 最终的标记化步骤总是使用空格作为分隔符。要根据特定的正则表达式模式拆分字符串,类似于 Python 的[re.split](https://docs.python.org/3/library/re.html#re.split),可以提供一个元组`('', ' ')`。 示例 基于`(patterns, replacements)`列表的正则表达式标记化。 ```py >>> 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, ' ')`列表的正则表达式标记化。 ```py >>> 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) ``` ```py forward(line: str) → List[str] ``` 参数: **lines**([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"))- 要分词的文本字符串。 返回: 正则表达式后的标记列表。 返回类型: List[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")] ## BERT 分词器 ```py class 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 分词器的转换。 基于 WordPiece 算法的论文:[`static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf`](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf) 后端内核实现取自[`github.com/LieluoboAi/radish`](https://github.com/LieluoboAi/radish)并进行了修改。 查看 PR [`github.com/pytorch/text/pull/1707`](https://github.com/pytorch/text/pull/1707)摘要以获取更多详细信息。 下面的代码片段显示了如何使用预训练的词汇文件来使用 BERT 分词器。 示例 ```py >>> from torchtext.transforms import BERTTokenizer >>> VOCAB_FILE = "https://huggingface.co/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*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"))- 预训练词汇文件的路径。路径可以是本地的或 URL。 + **do_lower_case**(*可选**[*[*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")*]*)- 指示是否进行小写处理。(默认值:True) + **strip_accents**(*可选**[*[*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")*]*)- 指示是否去除重音符号。(默认值:None) + **return_tokens**([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)"))- 指示是否返回标记。如果为 false,则返回相应的标记 ID 作为字符串(默认值:False) + **never_split** (*可选**[**列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]*) – 在标记化过程中不会被分割的标记集合。(默认值:无) ```py forward(input: Any) → Any ``` 参数: **input** (*Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*,* *列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]*) – 要应用标记器的输入句子或句子列表。 返回: 标记化文本 返回类型: Union[List[[str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")], List[List([str](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)"))]] ## VocabTransform ```py class torchtext.transforms.VocabTransform(vocab: Vocab) ``` 将输入标记批次转换为相应的标记 ID 的词汇转换 参数: **vocab** – `torchtext.vocab.Vocab`类的实例。 示例 ```py >>> 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 使用 XLM-RoBERTa 模型进行二进制文本分类](img/98241cb68ab73fa3d56bc87944e16fd8.png) SST-2 使用 XLM-RoBERTa 模型进行二进制文本分类 SST-2 使用 XLM-RoBERTa 模型进行二进制文本分类 ```py forward(input: Any) → Any ``` 参数: **input** (*Union**[**列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**,* *列表**[**列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]**]*) – 要转换为相应标记 ID 的输入标记批次 返回: 将输入转换为相应的标记 ID 返回类型: Union[List[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")], List[List[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")]]] ## ToTensor ```py class torchtext.transforms.ToTensor(padding_value: Optional[int] = None, dtype: dtype = torch.int64) ``` 将输入转换为 torch 张量 参数: + **padding_value** (*可选**[*[*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")*]*) – 用于使批次中每个输入的长度等于批次中最长序列的填充值。 + **dtype** ([`torch.dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "(在 PyTorch v2.1 中)")) – 输出张量的[`torch.dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "(在 PyTorch v2.1 中)") ```py forward(input: Any) → Tensor ``` 参数: **input** (*Union**[**列表**[*[*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")*]**,* *列表**[**列表**[*[*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")*]**]**]*) – 标记 ID 的序列或批次 返回类型: 张量 ## LabelToIndex ```py class torchtext.transforms.LabelToIndex(label_names: Optional[List[str]] = None, label_path: Optional[str] = None, sort_names=False) ``` 将标签从字符串名称转换为 ID。 参数: + **label_names** (*可选**[**列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]*) – 一个唯一标签名称的列表 + **label_path** (*可选**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]*) – 包含每行一个唯一标签名称的文件路径。请注意,应提供 label_names 或 label_path 之一,而不是两者都提供。 ```py forward(input: Any) → Any ``` 参数: **input** (*Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*,* *列表**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]*) – 要转换为相应 ID 的输入标签 返回类型: Union[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)"), List[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")]] ## Truncate ```py class torchtext.transforms.Truncate(max_seq_len: int) ``` 截断输入序列 参数: **max_seq_len** ([*int*](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")) – 输入序列的最大允许长度 使用`Truncate`的教程: ![SST-2 二进制文本分类与 XLM-RoBERTa 模型](img/98241cb68ab73fa3d56bc87944e16fd8.png) SST-2 二进制文本分类与 XLM-RoBERTa 模型 SST-2 二进制文本分类与 XLM-RoBERTa 模型 ```py forward(input: Any) → Any ``` 参数: **input** (*Union**[**List**[**Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]**]**,* *List**[**List**[**Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]**]**]**]*) – 要截断的输入序列或批处理序列 返回: 截断序列 返回类型: Union[List[Union[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")]], List[List[Union[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)"), [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")]]]] ## AddToken ```py class torchtext.transforms.AddToken(token: Union[int, str], begin: bool = True) ``` 在序列的开头或结尾添加标记 参数: + **token** (*Union**[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*]*) – 要添加的标记 + **begin** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")*,* *optional*) – 是否在序列的开头或结尾插入标记,默认为 True 使用`AddToken`的教程: ![SST-2 二进制文本分类与 XLM-RoBERTa 模型](img/98241cb68ab73fa3d56bc87944e16fd8.png) SST-2 二进制文本分类与 XLM-RoBERTa 模型 SST-2 二进制文本分类与 XLM-RoBERTa 模型 ```py forward(input: Any) → Any ``` 参数: **input** (*Union**[**List**[**Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]**]**,* *List**[**List**[**Union**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.12)")*,* [*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")*]**]**]**]*) – 输入序列或批处理 ## Sequential ```py class torchtext.transforms.Sequential(*args: Module) ``` ```py class torchtext.transforms.Sequential(arg: OrderedDict[str, Module]) ``` 一个容器,用于存储文本转换的序列。 使用`Sequential`的教程: ![SST-2 二进制文本分类与 XLM-RoBERTa 模型](img/98241cb68ab73fa3d56bc87944e16fd8.png) SST-2 二进制文本分类与 XLM-RoBERTa 模型 SST-2 二进制文本分类与 XLM-RoBERTa 模型 ```py forward(input: Any) → Any ``` 参数: **input** (任意) – 输入序列或批处理。输入类型必须受到序列中第一个转换的支持。 ## PadTransform ```py class torchtext.transforms.PadTransform(max_length: int, pad_value: int) ``` 使用给定的填充值将张量填充到固定长度。 参数: + **max_length** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.12)")) – 要填充到的最大长度 + **pad_value** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.12)")) – 用于填充张量的值 ```py forward(x: Tensor) → Tensor ``` 参数: **x** (*张量*) – 要填充的张量 返回: 张量使用填充值填充到最大长度 返回类型: 张量 ## StrToIntTransform ```py class torchtext.transforms.StrToIntTransform ``` 将字符串标记转换为整数(单个序列或批处理)。 ```py forward(input: Any) → Any ``` 参数: **输入**(*Union**[**List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**,* *List**[**List**[*[*str*](https://docs.python.org/3/library/stdtypes.html#str "(在 Python v3.12 中)")*]**]**]*) - 要转换的字符串标记的序列或批次 返回: 转换为相应标记 ID 的序列或批次 返回类型: Union[List[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")], List[List[[int](https://docs.python.org/3/library/functions.html#int "(在 Python v3.12 中)")]]] ## CharBPETokenizer ```py 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:参数 bpe_encoder_path:BPE 编码器 json 文件的路径。:param:类型 bpe_encoder_path:str:param:参数 bpe_merges_path:BPE 合并文本文件的路径。:param:类型 bpe_merges_path:str:param:参数 return_tokens:指示是否返回拆分的标记。如果为 False,则将返回编码的标记 ID(默认值:False)。:param:类型 return_tokens:bool:param:参数 unk_token:未知标记。如果提供,它必须存在于编码器中。:param:类型 unk_token:Optional[str]:param:参数 suffix:要用于每个作为单词结尾的子词的后缀。:param:类型 suffix:Optional[str]:param:参数 special_tokens:不应拆分为单个字符的特殊标记。如果提供,这些标记必须存在于编码器中。:param:类型 special_tokens:Optional[List[str]] ```py forward(input: Union[str, List[str]]) → Union[List, List[List]] ``` 模块的前向方法将字符串或字符串列表编码为标记 ID 参数: **输入** - 要应用分词器的输入句子或句子列表。 返回: 一个标记 ID 的列表或列表的列表