我正在用TypeScript开发一个机器学习算法,并有一个部分导数方法,旨在复制以下内容:这是我用来实现的递归方法:
private pd(a : Activation, w : Weight, t : number) : number { //Takes partial derivative of activation with respect to weight return sigDeriv(this.sums[t][a.l][a.j].val)*(a.l == w.l && a.j == w.j ? this.activations[t][a.l - 1][w.k].val : sumFunc(this.activations[t][a.l - 1].length, 1, async k => await this.weights[a.l][a.j][k].val*this.pd(this.activations[t][a.l - 1][k], w, t) ) ); }
问题是,即使达到了基础条件(a.l == w.l && a.j == w.j
),函数仍然继续执行,并最终到达输入层(那里没有权重),导致错误。这为什么会发生?我该如何修复?当我运行函数并记录基础情况的值时,它会在适当的时候返回true,但函数会继续执行,导致错误。
回答:
我发现需要将我的基础条件改得更通用。虽然第一个条件在找到被区分的权重乘以的激活时停止了函数,但函数继续尝试区分其余的激活,超出了权重对函数有影响的范围。基本上,我最终得到了∂/∂w(aw + a2w2 + ...)
,当区分该项时,pd
会返回乘以w
的激活,但会继续对其他项进行递归,而这些项不再受w
的影响,因此永远不会达到基础条件。因此,解决方案是在函数到达权重所在层时返回a
的值,因为上述导数计算结果为(a + 0 + ...)
。
private pd(a : Activation, w : Weight, t : number) : number { //Takes partial derivative of activation with respect to weight return sigDeriv(this.sums[t][a.l][a.j].val)*this.pdSum(a, w, t);}private pdSum(a : Activation, w : Weight, t : number) : number { //Handles sum statement in recursive derivative definition if(a.l == w.l) return this.activations[t][a.l - 1][w.k].val; //This line solves the problem return sumFunc(this.activations[t][a.l - 1].length, 1, async k => await this.weights[a.l][a.j][k].val*this.pd(this.activations[t][a.l - 1][k], w, t) );}