我正在使用 tf.raw_ops 命名空间创建自定义损失函数,以使用 keras 训练我的模型。这是我的损失函数:
Loss(pred,label)= { 0.0 if pred-label<=0.1, 1.0别处
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 它显示了哪些操作是可区分的,哪些不是。我所有的操作都是可微的。我不确定我错过了什么。任何帮助表示赞赏。