首页 > 解决方案 > Tensorflow:识别没有梯度的自定义损失函数中的操作

问题描述

我正在尝试在 Tensorflow 中创建自定义损失函数。该网络的目的是获取两个图像作为输入并输出一个预测两个图像之间角度差异的数字。因此,我的自定义损失函数必须根据输出中的数字旋转一个图像,并将旋转后的图像与另一张图像进行比较。

这是我为损失函数写的:

def test_custom_loss_function(y_true, y_pred):

y_true=K.cast(y_true, dtype='float32')
y_pred=K.cast(y_pred, dtype='float32')

fixed_filtered = tfa.image.median_filter2d(y_true[0,:,:])
moving_filtered = tfa.image.median_filter2d(y_true[1,:,:])

fixed_filtered=K.cast(fixed_filtered, dtype='float32')
moving_filtered=K.cast(moving_filtered, dtype='float32')

fixed_mask = tf.where(tf.math.less(tf.constant([20.0]), fixed_filtered),1.0,0.0)
moving_mask = tf.where(tf.math.less(tf.constant([20.0]), moving_filtered),1.0,0.0)

fixed_mask_r = tfa.image.rotate(fixed_mask, tf.constant(0.0))
moving_mask_r = tfa.image.rotate(moving_mask, y_pred[0])

fixed_mask_r=K.cast(fixed_mask_r, dtype='float32')
moving_mask_r=K.cast(moving_mask_r, dtype='float32')

loss = tf.reduce_sum(tf.math.squared_difference(fixed_mask_r,moving_mask_r))

return loss

我自己运行损失函数没有问题,但是,当我将它放入网络时,它会输出此错误:

ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

我怎样才能找到没有梯度的运算符?有什么可能的方法来解决它?

标签: pythontensorflow

解决方案


推荐阅读