首页 > 解决方案 > 如何在 tensorflow.keras 的功能 API 中使用 tf.debugging 函数?

问题描述

考虑以下使用 tf.keras 功能 API 构建基本模型的代码:

import numpy as np
import tensorflow as tf  # version 2.6.0
import tensorflow.keras.layers as layers

def build_model() -> tf.keras.models.Model:

    dtype = np.float32
    inputs_dict  = {"input_1": layers.Input(shape=(10, 20,), dtype=dtype)}
    input_1 = inputs_dict["input_1"]
    zero = tf.constant([0], dtype=dtype)
    tf.debugging.assert_less(zero, input_1)

    output_1 = layers.Dense(1, activation="relu")(input_1)

    outputs_dict = {"output_1": output_1}
    return tf.keras.models.Model(inputs=inputs_dict, outputs=outputs_dict)

model = build_model()
model.compile()

此代码产生:

TypeError: Could not build a TypeSpec for <tf.Operation 'tf.debugging.assert_less/assert_less/Assert/AssertGuard/Identity' type=Identity> with type Operation

我找不到任何关于 using 的好教程tf.debugging,更不用说专门使用 Functional API 中的模块了。它甚至可能或推荐吗?我确实找到了这个线程

如果您想将 tf.debugging.assert 编码为实际模型的一部分,您可以:

  1. 将它放在返回输入的 tf.keras.Lambda 层中(使用调试断言作为在 lambda 中运行的副作用),或者
  2. 将 tf.debugging 调用放在自定义层/自定义模型中。

但似乎Lambda方法不可取

Lambda 层是通过序列化 Python 字节码来保存的,这基本上是不可移植的。它们只能在保存它们的相同环境中加载。

而且我不愿意为我想在我的模型中做的每个断言添加一个自定义层。这看起来很恶心,尽管也许有一种干净的方式来做到这一点。

我希望 TF 能够以某种类似于 TF 的方式将断言合并到图表中,当模型实际在真实数据上执行时会有一些有用的行为。我在这里想念什么?有没有办法以便携、干净的方式完成这样的事情?

无论您推荐哪种方法(自定义层方法或其他方法),您介意提供一些示例代码吗?我没有在 TF 文档中找到大量好的示例代码。

标签: tensorflowtensorflow2.0tf.keras

解决方案


推荐阅读