递归函数中的基本情况不会停止递归打字稿

Base case in recursive function is not stopping recursion typescript

我正在使用 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),函数仍继续执行并最终到达输入层(没有权重的地方),从而导致错误。为什么会发生这种情况,我该如何解决? 当我 运行 函数并记录基本情况的值时,它会在适当的时候 return 为真,但函数会继续执行,导致错误。

首先是括号的问题。尝试:

((a.l == w.l && a.j == w.j) ? … : … )

因为这里只在a.j == w.j

上进行测试

(运算符 ? : 比 && 具有更高的优先级)

但是正如 Scott 所见,这并不能解决您的问题。我们没有看到完整的代码,所以不能确定,但​​这可能是同步性问题(我看到你正在使用 async/await)。如果 w 可以被异步修改,那么你的测试可能在不应该的时候为假…

我发现我需要将我的基本条件更改为更通用。虽然第一个条件在发现激活乘以被区分的权重时停止了函数,但函数继续尝试区分其余的激活,超出了权重对函数的影响。基本上,我在 ∂/∂w(aw + a2w2 + ...) 处结束,并且 pd 会 return 激活乘以 w 当该术语被区分时,但继续对其他术语进行递归,这不再受 w 影响,因此永远不会达到基本条件。因此,只要函数到达权重层,解决方案就是 return 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)
    );
}