You need to enable JavaScript to run this app. BERT中batch_encode_plus已废弃需用__call__替代,应如何正确调用?
优惠活动
大模型
产品
解决方案
定价
更多

BERT中batch_encode_plus已废弃需用__call__替代,应如何正确调用?

解决方法

__call__是Python类的内置魔法方法,不需要显式调用tokenizer.__call__(),直接将实例化后的分词器对象当作函数使用即可,参数和原batch_encode_plus完全兼容,不需要额外修改参数配置。

基础用法示例

首先实例化分词器:

from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") # 可替换为你使用的BERT预训练模型名

原batch_encode_plus写法(已废弃)

# 旧版废弃写法
output = tokenizer.batch_encode_plus(
    text_list,
    max_length=128,
    padding=True,
    truncation=True,
    return_tensors="pt"
)

新版替代写法

# 新版正确写法,完全等价于上面的旧版代码
output = tokenizer(
    text_list,
    max_length=128,
    padding=True,
    truncation=True,
    return_tensors="pt"
)

常见场景使用示例

  • 单句编码:替代原encode_plus
single_output = tokenizer(
    "这是待编码的单句文本",
    max_length=32,
    padding="max_length",
    truncation=True
)
# 输出字段包含input_ids、attention_mask、token_type_ids,和原`encode_plus`输出结构完全一致
  • 批量句对编码:适用于文本匹配、推理等场景
query_list = ["你多大了", "今天吃什么"]
answer_list = ["我今年20岁", "今天吃家常菜"]
pair_output = tokenizer(
    query_list,
    answer_list,
    max_length=64,
    padding=True,
    truncation=True,
    return_tensors="pt"
)

注意事项

如果你之前调用encode_plus输出不符合预期,是因为encode_plus仅支持单句输入,批量场景必须使用上面的直接调用分词器的写法。

内容的提问来源于stack exchange,提问作者coke979

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 17:36:00