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

Hugging Face tokenizer.batch_encode_plus 方法

batch_encode_plus批量处理多个文本 的方法,它比 encodeencode_plus 更适合大规模数据处理,适用于 文本分类、翻译、问答等 NLP 任务


1. batch_encode_plus 方法的基本用法

from transformers import AutoTokenizer

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

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

print(tokens)

示例输出

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

解释

  • input_ids:文本对应的 token ID 序列
  • token_type_ids:区分句子(0 代表第一个句子,1 代表第二个句子)
  • attention_mask:标记有效 token(1)和填充 token(0)

2. batch_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. batch_encode_plus 详细用法

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

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

tokens = tokenizer.batch_encode_plus(texts, max_length=5, truncation=True)
print(tokens["input_ids"])

输出

[
  [101, 17662, 18781, 2003, 102],
  [101, 10938, 2024, 6429, 102]
]
  • 文本被 截断,只保留 max_length=5 的 token。

3.2. 填充(padding

如果不同文本长度不一致,可以 自动填充 让它们对齐:

tokens = tokenizer.batch_encode_plus(texts, max_length=10, padding="max_length", truncation=True)
print(tokens["input_ids"])

输出

[
  [101, 17662, 18781, 2003, 2307, 999, 102, 0, 0, 0],
  [101, 10938, 2024, 6429, 999, 102, 0, 0, 0, 0]
]
  • 0 代表 [PAD]
  • attention_mask 也会更新:
[
  [1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
]

1 代表 有效 token0 代表 填充 token


3.3. 处理句子对(文本匹配、问答)

如果输入 两个句子batch_encode_plus 会自动添加 [SEP] 并生成 token_type_ids

pairs = [("Hugging Face is great!", "It provides NLP tools."),
         ("Transformers are powerful.", "They are used in AI.")]
tokens = tokenizer.batch_encode_plus(pairs)

print(tokens["input_ids"])

输出

[
  [101, 17662, 18781, 2003, 2307, 999, 102, 2009, 3641, 10336, 26642, 2476, 1012, 102],
  [101, 10938, 2024, 6429, 1012, 102, 2027, 2024, 2109, 1999, 9932, 1012, 102]
]
  • [SEP] 分隔句子
  • token_type_ids
[
  [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
  [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
]
  • 0 代表 第一个句子
  • 1 代表 第二个句子

3.4. 返回张量(PyTorch/TensorFlow)

如果要在 PyTorch 或 TensorFlow 中使用:

tokens = tokenizer.batch_encode_plus(texts, return_tensors="pt")  # PyTorch
print(tokens["input_ids"].shape)  # torch.Size([2, 7])
tokens = tokenizer.batch_encode_plus(texts, return_tensors="tf")  # TensorFlow
print(tokens["input_ids"].shape)  # (2, 7)

4. encode_plus vs batch_encode_plus

方法作用
encode_plus(text)处理单个文本
batch_encode_plus([text1, text2])批量处理多个文本

如果你的任务 包含多个文本,推荐使用 batch_encode_plus,它可以 自动填充、截断、返回 PyTorch/TensorFlow 张量


5. batch_encode_plusTrainer 训练时使用

微调 BERT 时batch_encode_plus 可用于数据预处理:

from datasets import load_dataset

dataset = load_dataset("imdb")

def preprocess_function(examples):
    return tokenizer.batch_encode_plus(examples["text"], truncation=True, padding="max_length")

encoded_dataset = dataset.map(preprocess_function, batched=True)

示例输出

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

6. 总结

batch_encode_plus 适用于批量文本处理,相比 encode_plus 支持多个文本同时编码,适用于 文本分类、机器翻译、问答任务

常见用法

  • tokenizer.batch_encode_plus(texts) → 批量编码
  • tokenizer.batch_encode_plus(texts, max_length=10, truncation=True) → 处理超长文本
  • tokenizer.batch_encode_plus(texts, padding="max_length") → 填充到固定长度
  • tokenizer.batch_encode_plus(texts, return_tensors="pt") → 返回 PyTorch 张量
  • tokenizer.batch_encode_plus([(text1, text2)]) → 处理句子对任务

如果你的任务 需要处理多个文本,并希望自动填充、截断、返回 attention_mask,建议 使用 batch_encode_plus

基于BERT的文本分类是一种常见的自然语言处理任务,利用BERT(Bidirectional Encoder Representations from Transformers)模型进行文本分类的源代码通常包括以下几个步骤: 1. **数据预处理**:将文本数据转换为BERT模型可以接受的格式。 2. **加载预训练模型**:使用Hugging FaceTransformers库加载预训练的BERT模型和分词器。 3. **定义分类模型**:在BERT模型的基础上添加一个全连接层来进行分类。 4. **训练模型**:使用训练数据进行模型训练。 5. **评估模型**:使用验证集或测试集评估模型性能。 以下是一个简单的基于BERT的文本分类源代码示例: ```python import torch from torch.utils.data import DataLoader, Dataset from transformers import BertTokenizer, BertForSequenceClassification from transformers import AdamW, get_linear_schedule_with_warmup import pandas as pd # 自定义数据集类 class TextDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_len): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_len = max_len def __len__(self): return len(self.texts) def __getitem__(self, idx): text = str(self.texts[idx]) label = self.labels[idx] encoding = self.tokenizer.encode_plus( text, add_special_tokens=True, max_length=self.max_len, return_token_type_ids=False, padding='max_length', truncation=True, return_attention_mask=True, return_tensors='pt', ) return { 'text': text, 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'labels': torch.tensor(label, dtype=torch.long) } # 加载数据 df = pd.read_csv('data.csv') texts = df['text'].tolist() labels = df['label'].tolist() # 划分训练集和验证集 from sklearn.model_selection import train_test_split train_texts, val_texts, train_labels, val_labels = train_test_split(texts, labels, test_size=0.2) # 初始化分词器和数据集 tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') train_dataset = TextDataset(train_texts, train_labels, tokenizer, max_len=128) val_dataset = TextDataset(val_texts, val_labels, tokenizer, max_len=128) # 初始化数据加载器 train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=16, shuffle=False) # 加载预训练模型 model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) # 训练模型 device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model = model.to(device) optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False) total_steps = len(train_loader) * 2 scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps) for epoch in range(2): model.train() for batch in train_loader: optimizer.zero_grad() input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['labels'].to(device) outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels) loss = outputs.loss loss.backward() optimizer.step() scheduler.step() # 验证模型 model.eval() correct_predictions = 0 for batch in val_loader: with torch.no_grad(): input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['labels'].to(device) outputs = model(input_ids=input_ids, attention_mask=attention_mask) _, preds = torch.max(outputs.logits, dim=1) correct_predictions += torch.sum(preds == labels) print(f'Epoch {epoch + 1}, Accuracy: {correct_predictions.double() / len(val_dataset)}') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

彬彬侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值