You need to enable JavaScript to run this app. n-gram文本生成实现时scipy报IndexError: index -1 is out of bounds错误
优惠活动
大模型
产品
解决方案
定价
更多

n-gram文本生成实现时scipy报IndexError: index -1 is out of bounds错误

错误根因

你遇到的错误本质是传入scipy.stats.multinomial.rvs的概率数组为空:

  • 生成文本过程中,动态更新的二元前缀start_word,没有在训练用的三元组语料库中出现过,导致TrTrigramPbs[start_word].samples()返回空列表
  • 遍历空列表生成的word_probabilities是空数组,scipy内部处理概率数组时访问最后一位p[..., -1]就会触发索引越界
  • 触发时机不固定是因为采样过程是随机的,只有刚好遇到语料中不存在的二元前缀才会报错,运行时间越长、采样次数越多,触发概率越高
修复方案

1. 新增空概率数组兜底逻辑

在调用multinomial.rvs前先判断概率数组是否为空,遇到空数组时直接做兜底处理,避免程序崩溃,修改对应代码段如下:

for i in range(10):
    probable_words = list(TrTrigramPbs[start_word].samples())
    word_probabilities = [TrTrigramPbs[start_word].prob(word) for word in probable_words]
    # 新增空值判断
    if not word_probabilities:
        # 兜底方案1:随机重置前缀,重新生成
        rand = random.choice(random_choice_list)
        start_word = ('<s>', rand)
        continue
        # 兜底方案2:回退到全局一元词库采样
        # sampled_word = random.choice(filtered_tokens)
        # start_word = (start_word[1], sampled_word)
        # data.append(sampled_word)
        # continue
    result = stats.multinomial.rvs(1, word_probabilities)
    index_of_probable_word = list(result).index(1)
    start_word = (start_word[1], probable_words[index_of_probable_word])
    data.append(start_word[1])

2. 额外优化建议

  • 把三元组构建、概率分布计算的逻辑移到singleverse函数外,全局只计算一次,不要每次调用函数都重复遍历语料,可大幅提升运行效率
  • 替换nltk.MLEProbDist为带平滑的概率分布(如nltk.LaplaceProbDist),可降低未见过的前缀出现概率

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

相关产品推荐
方舟 Agent Plan

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

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