tensorflow - ValueError:定义自定义损失函数时没有为任何变量提供梯度
问题描述
下面你可以找到我的自定义损失函数。
def custom_loss_function(y_true, y_pred):
y_pred_bool = tf.math.less_equal(y_pred, tf.constant(0.5))
y_pred_float = 1 - tf.cast(y_pred_bool, dtype=tf.int32)
y_true = tf.cast(y_true, dtype=tf.int32)
mask_bool_loss = tf.math.less(y_true, tf.constant(0))
mask_loss = 1 - tf.cast(mask_bool_loss, dtype=tf.int32)
mask = tf.math.reduce_min(mask_loss, axis=2)
y_multiply = tf.math.multiply(y_true, y_pred_float)
y = tf.math.reduce_sum(y_multiply, axis=2)
y_loss = 1 - y
y_loss = tf.math.multiply(y_loss, mask)
return y_loss
我知道 tensorflow 的一些函数是不可微的,但我真的不知道哪些函数或如何绕过它?对我有什么建议吗?
我收到此错误:
ValueError: No gradients provided for any variable: ['bidirectional_7/forward_lstm_7/lstm_cell_22/kernel:0'/, ...
解决方案
一旦将变量转换为 int 或 bool,所有梯度信息都会丢失。因此,第一行中的渐变被破坏了。
y_pred_bool = tf.math.less_equal(y_pred, tf.constant(0.5))
这就是我们通常使用二元交叉熵之类的东西的原因,因为它为我们提供了不可微分的 0-1 损失的可微近似。
推荐阅读
- javascript - 在 katalon Selenium 中创建 Chrome 配置文件
- amazon-web-services - AWS - 如何找到使用层的 lambda 函数的总大小
- oop - 面向对象编程和过程编程有什么区别?
- jdo - 使用接口类型时,乐观锁定中的数据核和双向 1-N 违反参照完整性约束
- c# - 使用 C# 应用程序中的 OleDb 在 Oracle 数据库中插入图像
- php - 控制器没有来自中间件的更改请求
- sql-server - 插入后不触发 SQL 触发器
- windows - 为什么在我使用 Visual Studio Native Tool x86 构建 OpenSSL 1.1.1d 后这些测试会失败?
- redis - 在 Ubuntu 19.10 上无法访问新安装的 redis(5.0.5)
- swift - 是否可以为 AVPlayerItem URLRequest 配置自定义标头?