python - TensorFlow自定义损失函数错误:没有为任何变量提供梯度
问题描述
我正在使用tf.raw_ops命名空间创建一个自定义损失函数,以使用 keras 训练我的模型。这是我的损失函数:
Loss(pred,label)= { 0.0 if pred−label<=0.1, 1.0 else
comparing_tensor = tf.convert_to_tensor([0.1, 0.1, 0.1])
def custom_loss(y_pred, y_true):
loss_tensor = tf.raw_ops.Abs(x=y_pred - y_true) # get the abs diff between y_true and y_pred
boolean_tensor = tf.raw_ops.Greater(x=loss_tensor, y=comparing_tensor) # get a boolean tensor based on Greater operation. Example: [True, False, True]
binary_tensor = tf.raw_ops.Cast(x=boolean_tensor, DstT=tf.float32) # convert boolean to bianry tensor Example: [1.0, 0.0, 1.0]
mean_tensor= tf.raw_ops.Mean(input=binary_tensor, axis=-1) # get mean of binary tensor, 2/3=0.66
loss = tf.raw_ops.Reshape(tensor=mean_tensor, shape=(1,1), name=None) # reshape mean tensor to get desired shape
return loss
然后我在我的
Keras.model.compile(opt=SDG, loss=custom_loss, metrics=['mse])
我收到一个错误
ValueError:没有为任何变量提供梯度:['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'conv2d_2/kernel:0', 'conv2d_2/bias:0'、'conv2d_3/kernel:0'、'conv2d_3/bias:0'、'conv2d_4/kernel:0'、'conv2d_4/bias:0'、'dense/kernel:0'、'dense /bias:0', 'x/kernel:0', 'x/bias:0'].**
我知道这可能是因为tf.operations
我使用的一些是不可区分的,或者没有渐变。但是,我已经检查了这个页面https://docs.w3cub.com/tensorflow~2.3/raw_ops它显示了哪些操作是可区分的,哪些不是。我所有的操作都是可区分的。我不确定我错过了什么。任何帮助表示赞赏。
解决方案
推荐阅读
- javascript - 如何使用 mocha chai 和酶对道具的状态进行单元测试?
- python-3.x - 请求与 webbrowser 中相同的网页
- javascript - Vue.js Axios 发布发送空值
- c# - EF Core - 自从使用 SQL ON UPDATE CURRENT_TIMESTAMP 加载实体后,数据可能已被修改或删除
- asp.net-core - ASP.NET Core 3.0 未在 Visual Studio 2019 上显示
- python - Python - 使用 pandas 用列表覆盖 CSV 列
- firebase - 我需要在颤动中向特定用户(不是全部)显示特定屏幕
- javascript - 抓取自定义属性值包含字符串的元素 - xpath selenium
- javascript - 通过用户脚本阻止警报
- jsonschema - 使用 JSON Schema 进行验证时,是不是递归验证子实体?