我正在研究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,但是该函数将继续执行,从而导致错误。
答案 0 :(得分:1)
首先,有一个括号问题。试试:
((a.l == w.l && a.j == w.j) ? … : … )
因为在这里,测试仅在a.j == w.j
(运算符?:比&&拥有更高的优先级)
但是,正如Scott所见,这无法解决您的问题。我们没有看到完整的代码,因此无法确定,但这可能是同步问题(我看到您正在使用async / await)。如果w可以被异步修改,那么您的测试可能在不应该修改的情况下为假。
答案 1 :(得分:0)
我发现我需要更改基本条件以使其更通用。当第一个条件使激活乘以要区分的权重时停止了功能时,功能继续尝试区分其余的激活,权重对功能的影响超出了此范围。基本上,我以∂/∂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)
);
}