You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遇到AssertionError提示需向方法提供encoding或编码列表该如何解决?

报错触发原因与解决方案

你遇到的AssertionError: You should supply an encoding or a list of encodings to this method 直译是你需要为该方法传入一个编码对象或编码对象列表,触发原因与解决方法如下:

触发原因

  • 调用的方法要求必须传入分词器(tokenizer)编码方法返回的结构化编码对象作为入参,但实际传入的是普通字符串、单独的token id列表等不符合要求的参数
  • 传参时参数顺序错误,将其他值传入了encoding参数的位置,导致方法未接收到符合要求的编码对象

解决方式

  • 调整编码逻辑,不要直接传入encode方法返回的纯id列表,改为调用分词器的__call__、encode_plus或batch_encode_plus方法,获取完整的结构化编码对象作为入参
    示例代码如下:

错误写法

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
text = "sample text"
# 错误:仅获取纯token id列表,缺少方法需要的其他结构化字段
input_ids = tokenizer.encode(text)
target_method(input_ids)

正确写法

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
text = "sample text"
# 正确:调用__call__方法返回完整编码对象
encoding = tokenizer(text)
target_method(encoding)
  • 若已经生成了符合要求的编码对象仍报错,检查传参顺序,可显式指定参数名传参避免位置错误,例如:target_method(encoding=encoding)
  • 批量处理场景下,调用batch_encode_plus生成批量编码对象列表传入即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:45:04