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

GAN生成MIDI训练正常,生成阶段报KeyError:260错误原因求解

报错问题排查与修复

根因定位

KeyError: 260是因为你换算得到的整数260不存在于int_to_note字典的键中,具体逻辑如下:

  • int_to_note字典由训练集中所有去重后的音符枚举生成,键的合法范围是0 ~ 音符总数-1,报错260说明你的训练集最多只有260种不同音符,最大合法键是259
  • 你当前使用的预测值反换算逻辑x*242+242没有做边界限制,生成器输出的浮点数x超出预期范围时,换算后就会得到超出合法范围的整数
  • 训练阶段使用的都是真实音符的归一化值,永远在合法范围内,所以不会触发报错,只有生成阶段用随机噪声预测时才会出现该问题

修复方案

步骤1:增加合法值截断逻辑

直接修改generate方法中的预测值换算代码,新增边界判断保证结果落在合法范围内:

def generate(self, input_notes):
    # Get pitch names and store in a dictionary
    notes = input_notes
    pitchnames = sorted(set(item for item in notes))
    int_to_note = dict((number, note) for number, note in enumerate(pitchnames))
    # 新增:获取合法音符总数对应最大ID
    max_note_id = len(pitchnames) - 1
    
    # Use random noise to generate sequences
    noise = np.random.normal(0, 1, (1, self.latent_dim))
    predictions = self.generator.predict(noise)
    
    # 修改:换算后先截断到0~max_note_id范围再转整数
    pred_notes = [max(0, min(int(x*242+242), max_note_id)) for x in predictions[0]]
    pred_notes = [int_to_note[x] for x in pred_notes]
    
    create_midi(pred_notes, 'gan_final')

步骤2(可选优化):修正反归一化公式

如果你的生成器输出层使用的是tanh激活(输出范围固定为[-1,1]),且训练阶段你将原始的0~241的音符ID归一化到了[-1,1],可以替换更合理的反归一化公式,从源头减少超出范围的概率:

# 替换原有的x*242+242逻辑
pred_notes = [int((x + 1) / 2 * max_note_id) for x in predictions[0]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:54:05