tensorflow - 如何在 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 编码为实际模型的一部分,您可以:
- 将它放在返回输入的 tf.keras.Lambda 层中(使用调试断言作为在 lambda 中运行的副作用),或者
- 将 tf.debugging 调用放在自定义层/自定义模型中。
但似乎该Lambda
方法不可取
Lambda 层是通过序列化 Python 字节码来保存的,这基本上是不可移植的。它们只能在保存它们的相同环境中加载。
而且我不愿意为我想在我的模型中做的每个断言添加一个自定义层。这看起来很恶心,尽管也许有一种干净的方式来做到这一点。
我希望 TF 能够以某种类似于 TF 的方式将断言合并到图表中,当模型实际在真实数据上执行时会有一些有用的行为。我在这里想念什么?有没有办法以便携、干净的方式完成这样的事情?
无论您推荐哪种方法(自定义层方法或其他方法),您介意提供一些示例代码吗?我没有在 TF 文档中找到大量好的示例代码。
解决方案
推荐阅读
- python - 如果数据库(如 MySQL)中的任何数据更新,是否可以触发脚本或程序?
- javascript - 如何在顶部显示成功消息,而它在内部 div
- rest - 理解 Go 中的 http handlerfunc 包装器技术
- r - 如何在我读取的多个数据集中添加一个带有 mutate () 的列?
- string - 如何将具有空终止字符的字节数组转换为 Kotlin 中的字符串?
- java - Gradle - 运行时异常:(
- flask - 添加默认值后,Flask wtf-form 不验证?
- azure - 将 NSG 关联到 foreach 循环 Powershell 中的子网
- sql - 在标准 RDBMS 中使用 HAVING 的规则
- java - 一次扫描字符串中的前 2 个字符