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

如何解决DistilBERT Tokenizer处理预分词句子时出现的类型错误问题

错误原因

这个报错的核心是sentences列表中存在不符合预分词输入格式的异常数据:is_split_into_words=True要求输入必须是外层为句子列表,内层每个元素为全字符串的单词列表的二维结构,只要有一条数据不符合该结构,Fast分词器的批量校验逻辑就会抛出该错误。你测试前76条正常,说明异常数据出现在第77条及之后的位置。

排查异常数据的方法

运行以下代码定位所有不符合格式的异常数据:

for idx, sen in enumerate(sentences):
    # 校验当前条目是否为列表
    if not isinstance(sen, list):
        print(f"异常索引{idx}:不是列表,类型为{type(sen)},内容:{sen}")
        continue
    # 校验是否为空列表
    if len(sen) == 0:
        print(f"异常索引{idx}:为空列表")
    # 校验列表内所有元素是否为字符串
    for w_idx, word in enumerate(sen):
        if not isinstance(word, str):
            print(f"异常索引{idx},单词索引{w_idx}:不是字符串,类型为{type(word)},内容:{word}")

解决方案

根据排查到的异常类型对应处理即可:

  • 若异常为空列表:可以直接过滤该条数据,也可以填充占位符["<EMPTY>"]补全格式
  • 若异常为非字符串元素:将元素统一转为字符串即可,处理代码:
    sentences = [[str(word) for word in sen] for sen in sentences]
    
  • 若异常为嵌套层级错误(比如某条数据多套了一层列表):将嵌套结构拍平为单层字符串列表即可
  • 如果不想排查数据,也可以用单条分词再合并的方式绕开批量校验逻辑,代码如下:
    from transformers import DistilBertTokenizerFast
    tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')
    
    input_ids = []
    attention_masks = []
    for sen in sentences:
        encoded = tokenizer(
            sen, truncation=True, is_split_into_words=True, 
            padding='max_length', max_length=120
        )
        input_ids.append(encoded["input_ids"])
        attention_masks.append(encoded["attention_mask"])
    
    # 合并为和批量处理一致的输出格式
    tokenized_input = {"input_ids": input_ids, "attention_mask": attention_masks}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:24:08