首页 > 解决方案 > 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它显示了哪些操作是可区分的,哪些不是。我所有的操作都是可区分的。我不确定我错过了什么。任何帮助表示赞赏。

标签: pythontensorflowkerasloss-function

解决方案


推荐阅读