嗨,我一直试图在keras中为骰子误差系数定制一个损失函数。它的实现在tensorboard中,我尝试在keras中使用与tensorflow相同的函数,但当我使用模型时,它一直返回一个NoneType。在批处理或模型上训练。在模型的度量中使用时,它会给出适当的值。能不能请人帮我做点什么?我试过使用像ahundt的Keras FCN这样的库,在那里他使用了定制的丢失函数,但似乎都不起作用。代码中的目标和输出分别是yútrue和yúpred,如keras中loss.py文件中所用。
def dice_hard_coe(target, output, threshold=0.5, axis=[1,2], smooth=1e-5):
"""References
-----------
- `Wiki-Dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_
"""
output = tf.cast(output > threshold, dtype=tf.float32)
target = tf.cast(target > threshold, dtype=tf.float32)
inse = tf.reduce_sum(tf.multiply(output, target), axis=axis)
l = tf.reduce_sum(output, axis=axis)
r = tf.reduce_sum(target, axis=axis)
hard_dice = (2. * inse + smooth) / (l + r + smooth)
hard_dice = tf.reduce_mean(hard_dice)
return hard_dice
在Keras中实现参数化的自定义丢失函数有两个步骤。首先,编写系数/度量的方法。第二,编写一个包装函数,按照Keras需要的方式对内容进行格式化。
实际上,使用Keras后端而不是tensorflow直接用于像DICE这样的简单的自定义丢失函数要干净得多。下面是这样实现的系数示例:
现在是棘手的部分。Keras损失函数只能以(y_true,y_pred)作为参数。所以我们需要一个单独的函数来返回另一个函数。
最后,您可以在Keras compile中按如下方式使用它。
相关问题 更多 >
编程相关推荐