Java中调用方法后Neuron_类weights属性未更新问题排查
权重未更新问题的修复方案
问题核心
你的权重更新逻辑存在重复抵消问题:同一个神经元会被先后执行增加和减少权重的操作,最终权重没有实际变化。
问题代码分析
看你在NeuralNetwork_中的更新循环:
if(biggestIndex != correctIndex) { System.out.println("Wrong output, changing weights"); for (int i = 0; i < this.neurons.length; i++) { for (int j = 0; j < outputNeurons.length; j++) { System.out.println("Changing weights for neuron " + i + " for output " + outputNeurons[j]); if (j == correctIndex) { this.neurons[i].increaseWeight(inputs); } else if (j == biggestIndex) { this.neurons[i].decreaseWeight(inputs); } } } }
外层循环遍历所有输出神经元,内层循环遍历所有输出标签。由于correctIndex != biggestIndex(进入该分支的前提),每个神经元都会被同时触发增加和减少操作,两次更新的效果完全抵消,导致权重数值没有变化。
修复后的代码
只需要针对正确类别和错误预测的神经元分别操作,不需要嵌套遍历所有输出标签:
if(biggestIndex != correctIndex) { System.out.println("Wrong output, changing weights"); // 给对应正确类别的神经元增加权重 this.neurons[correctIndex].increaseWeight(inputs); // 给对应错误预测的神经元减少权重 this.neurons[biggestIndex].decreaseWeight(inputs); System.out.println("Updated weights for correct neuron " + correctIndex + " and wrong neuron " + biggestIndex); }
额外检查项
- 确认
learningRate设置了非零的合理值(比如0.01或0.1),如果学习率为0,权重不会发生变化 - 打印权重时,确保获取的是
neurons数组中对应神经元的实时weights值,而非初始化时的副本
内容的提问来源于stack exchange,提问作者Sultan Delen
相关产品推荐
相关产品推荐

