如何在定制的 Tensorflow 模型中打破循环(使用 Keras)

How to break a loop inside a custom made Tensorflow model (using Keras)

我正在 Tensorflow 2.0 中构建机器学习应用程序。
我尝试通过在调用函数中迭代事实时打破 for 循环(如果满足条件)来优化计算效率,但它 returns 一个错误说:

OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed: AutoGraph did not convert this function. Try decorating it directly with u/tf.function.
(I've also tried adding a tf function the call method

有人知道如何在自定义张量流模型中打破调用函数内的 for 循环并执行逻辑吗?

我的代码
def call(self, inputs, questions):
    episode = tf.zeros(shape=(self.batch_size, self.units))
    memory = questions
    facts = self.split(self.transpose(self.cast(inputs, tf.float32), perm?(1,0,2)), self.facts_len)

    for _ in range(self.passes):
        for c in facts:
            c = tf.squeeze(c)
            g = self.attention(c, memory, questions)

            episode = (
                g * self.rnn(tf.expand_dims(c,-1), memory)[1] + (1-g) * episode
            )

        # Generates next memory
        _, memory = self.rnn(self.expand(episode, -1), memory)
    return memory

您应该能够在您的逻辑中使用 break。 Keras 将 autograph 应用到 call,所以它应该可以工作,但我的猜测是你需要更改外循环:for _ in tf.range(self.passes),如果 break 在内循环内,请确保 facts也是张量。

有关详细信息,请参阅此 guide and the reference 焦点。