typescript - 递归函数中的基本情况不会停止递归 typescript

标签 typescript recursion machine-learning neural-network calculus

我正在 TypeScript 中研究机器学习算法,并且有一个偏导数方法旨在复制此算法: enter image description here 这是我的递归方法:

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,但该函数将继续执行,从而导致错误。

最佳答案

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

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

因为这里只对a.j == w.j进行测试

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

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

关于typescript - 递归函数中的基本情况不会停止递归 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56496399/

相关文章:

types - 如何声明 TypeScript 导入 * 类型?

javascript - TypeScript 导入与 ES6 对象解构

angular - 将数据从模态返回到 Angular 中的组件

machine-learning - 通过机器学习选择特征

machine-learning - 处理文本数据以进行分类

python - 如何从检查点文件加载微调的 pytorch Huggingface bert 模型?

angular - 使用 Angular 替换数值和斜杠

python 递归实现词组搜索。如何进行?

Python3 和递归类

python - 为什么这个递归求和函数返回 None?