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

使用RoBERTa Transformer做NER时出现索引越界错误求助

诊断与解决方案

这个索引越界错误的核心原因是:你传入word_ids()的batch_index=1超出了当前批次的样本数量范围。

问题根源

当你单独运行分词时,可能是处理单一样本;但调用tokenize_and_align_labels函数时,如果是通过Dataset.map()等方式处理,默认是单样本批次(batched=False),此时tokenized_inputs只包含1个样本,合法的batch_index只能是0,使用1自然触发索引越界。

具体修复步骤

  1. 调整函数调用方式
    如果是用Hugging Face Dataset的map方法调用你的函数,务必开启batched=True,确保批次包含多个样本:

    dataset = dataset.map(tokenize_and_align_labels, batched=True)
    
  2. 动态适配批次索引
    若需要兼容单样本和多样本场景,可在函数内部先获取当前批次的样本数,再安全获取word_ids:

    def tokenize_and_align_labels(examples):
        # 原有分词逻辑
        tokenized_inputs = tokenizer(examples["text"], truncation=True, padding="max_length")
        
        # 安全获取word_ids
        batch_size = len(tokenized_inputs["input_ids"])
        target_batch_index = 1
        if target_batch_index >= batch_size:
            # 若目标索引超出范围,回退到最后一个样本
            word_ids = tokenized_inputs.word_ids(batch_index=batch_size - 1)
        else:
            word_ids = tokenized_inputs.word_ids(batch_index=target_batch_index)
        
        # 后续标签对齐逻辑
        # ...
        return tokenized_inputs
    
  3. 验证业务逻辑必要性
    确认是否真的需要固定取batch_index=1的样本。如果是调试需求,可临时打印批次大小;如果是业务需求,需确保调用函数时的批次大小至少为2。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:42:06