TensorFlow 自定义损失函数错误:没有为任何变量提供梯度

问题描述

我正在使用 tf.raw_ops 命名空间创建自定义损失函数,以使用 keras 训练我的模型。这是我的损失函数

Loss(pred,label)= { 0.0 if pred-label

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','密集/内核:0','dense/bias:0','x/kernel:0','x/bias:0'].**

我知道这可能是因为我使用的某些 tf.operations 不可微,或者没有渐变。但是,我检查了这个页面 https://docs.w3cub.com/tensorflow~2.3/raw_ops显示了哪些操作是可区分的,哪些不是。我所有的操作都是可微的。我不确定我错过了什么。任何帮助表示赞赏。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)