【Hugging Face】tokenizer.encode_plus() 方法:文本编码(返回 input ids、attention mask、token type IDs)

Hugging Face tokenizer.encode_plus 方法

tokenizer.encode_plus 是 Hugging Face 提供的 文本编码方法,相比 tokenizer.encode,它 返回更丰富的编码信息,如 attention mask、token type IDs,适用于 文本分类、问答、NER 等 NLP 任务


1. encode_plus 方法的基本用法

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

text = "Hugging Face is great!"
tokens = tokenizer.encode_plus(text)

print(tokens)

示例输出

{
  'input_ids': [101, 17662, 18781, 2003, 2307, 999, 102],
  'token_type_ids': [0, 0, 0, 0, 0, 0, 0],
  'attention_mask': [1, 1, 1, 1, 1, 1, 1]
}

解释

  • input_ids → token ID 序列(包括 [CLS][SEP]
  • token_type_ids → 句子区分标记(用于句子对任务)
  • attention_mask → 指示 有效 token(1)填充 token(0)

2. encode_plus 的常见参数

参数作用默认值
text输入文本必需
add_special_tokens是否添加 [CLS][SEP]True
max_length最大序列长度None
padding是否填充False
truncation是否截断False
return_tensors返回 torchtfnpNone
return_attention_mask是否返回 attention_maskTrue
return_token_type_ids是否返回 token_type_idsTrue

3. encode_plus 详细用法

3.1. 禁用特殊标记

默认情况下,encode_plus 会添加 [CLS][SEP],如果 不需要这些标记

tokens = tokenizer.encode_plus(text, add_special_tokens=False)
print(tokens)

输出

{
  'input_ids': [17662, 18781, 2003, 2307, 999],
  'token_type_ids': [0, 0, 0, 0, 0],
  'attention_mask': [1, 1, 1, 1, 1]
}

3.2. 处理超长文本(截断)

如果文本 超过 BERT 允许的最大长度(512),可以手动截断:

tokens = tokenizer.encode_plus(text, max_length=5, truncation=True)
print(tokens)

输出

{
  'input_ids': [101, 17662, 18781, 2003, 102],  # 截断
  'token_type_ids': [0, 0, 0, 0, 0],
  'attention_mask': [1, 1, 1, 1, 1]
}

3.3. 处理句子对任务

如果输入 两个句子(如文本匹配、问答任务),encode_plus 会自动添加 [SEP] 并生成 token_type_ids

sentence1 = "Hugging Face is amazing."
sentence2 = "It provides NLP tools."

tokens = tokenizer.encode_plus(sentence1, sentence2)
print(tokens)

输出

{
  'input_ids': [101, 17662, 18781, 2003, 6429, 1012, 102, 2009, 3641, 10336, 26642, 2476, 1012, 102],
  'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
  'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
}
  • token_type_ids
    • 0 代表 第一个句子
    • 1 代表 第二个句子

3.4. 填充(padding

如果想让所有 input_ids 变为相同长度:

tokens = tokenizer.encode_plus(text, max_length=10, padding="max_length", truncation=True)
print(tokens)

输出

{
  'input_ids': [101, 17662, 18781, 2003, 2307, 999, 102, 0, 0, 0],  # 用 [PAD] 填充
  'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  'attention_mask': [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]  # 填充部分 attention_mask=0
}

3.5. 返回张量(PyTorch/TensorFlow)

如果要在 PyTorch 或 TensorFlow 中使用,需要返回 tensor

tokens = tokenizer.encode_plus(text, return_tensors="pt")  # PyTorch
print(tokens["input_ids"].shape)  # torch.Size([1, 7])
tokens = tokenizer.encode_plus(text, return_tensors="tf")  # TensorFlow
print(tokens["input_ids"].shape)  # (1, 7)

4. encode vs encode_plus vs batch_encode_plus

方法作用
encode(text)编码单个文本,返回 token ID
encode_plus(text)返回 input_idsattention_masktoken_type_ids
batch_encode_plus([text1, text2])批量编码多个文本

4.1. batch_encode_plus(批量处理)

如果 要处理多个句子,使用 batch_encode_plus

texts = ["Hugging Face is great!", "Transformers are amazing!"]
tokens = tokenizer.batch_encode_plus(texts, padding=True, truncation=True)
print(tokens)

输出

{
  'input_ids': [[101, 17662, 18781, 2003, 2307, 999, 102],
                [101, 10938, 2024, 6429, 999, 102, 0]],
  'attention_mask': [[1, 1, 1, 1, 1, 1, 1],
                     [1, 1, 1, 1, 1, 1, 0]]
}

5. 总结

encode_plus 方法 encode 更强大,适用于 文本分类、问答等任务

常见用法

  • tokenizer.encode_plus(text) → 编码文本
  • tokenizer.encode_plus(text, add_special_tokens=False) → 不加 [CLS] [SEP]
  • tokenizer.encode_plus(text, max_length=10, truncation=True) → 处理超长文本
  • tokenizer.encode_plus(sentence1, sentence2) → 处理句子对
  • tokenizer.encode_plus(text, return_tensors="pt") → 返回 PyTorch 张量
  • tokenizer.batch_encode_plus([text1, text2]) → 批量处理文本

如果你的任务 需要 attention_masktoken_type_ids,建议使用 encode_plusbatch_encode_plus

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彬彬侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值