如何解决如何在keras中创建自定义损失函数? 自定义加权二进制交叉熵
我正在创建一个完全卷积的神经网络,只要输入的图像能够识别其中的区域(黑色,0),还可以识别背景(白色,255)。 我的目标是二值化图像(范围为0-255),我想在两个语义类(0或255)之间取得一些平衡。 实际上,我获得的“特殊”区域(0)的数量是背景区域(255)的1.8倍,因此我需要抵消这种影响,并且我想对事实做出更多的惩罚,以避免在背景上出错只能预测特殊区域。
我尝试遵循一些相关主题,这似乎并不难,但是我陷入了实施过程,我真的不知道为什么。
每次我的实现都在编译阶段工作时,但只有在拟合步骤中,它才会返回错误。
这是我到目前为止尝试过的:
import keras.backend as kb
def custom_binary_crossentropy(y_true,y_pred):
"""
Used to reequilibrate the data,as there is more black (0.,articles),than white (255.,non-articles) on the pages.
"""
if y_true >=128: # Half the 0-255 range
return -1.8*kb.log(y_pred/255.)
else:
return -kb.log(1-(y_pred/255.))
但是它返回了:
InvalidArgumentError: The second input must be a scalar,but it has shape [16,256,256]
[[{{node gradient_tape/custom_binary_crossentropy/cond/StatelessIf/gradient_tape/custom_binary_crossentropy/weighted_loss/Mul/_17}}]] [Op:__inference_train_function_24327]
Function call stack:
train_function
我不太了解这个错误。
我以前尝试过:
def custom_binary_crossentropy(y_true,y_pred):
"""
Used to reequilibrate the data,non-articles) on the pages.
"""
if y_true >=128: # Half the 0-255 range
return 1.8*keras.losses.BinaryCrossentropy(y_true,y_pred)
else:
return keras.losses.BinaryCrossentropy(y_true,y_pred)
但是我得到了:
TypeError: in user code:
/Users/axeldurand/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:806 train_function *
return step_function(self,iterator)
<ipython-input-67-7b6815236f63>:6 custom_binary_crossentropy *
return -1.8*keras.losses.BinaryCrossentropy(y_true,y_pred)
TypeError: unsupported operand type(s) for *: 'float' and 'BinaryCrossentropy'
我有点困惑,Keras总是让它变得如此简单,我必须省略一些简单的东西,但我真的不明白。
解决方法
您以错误的方式使用keras.losses.BinaryCrossentropy
。您实际上需要此损失的功能版本,即tf.keras.losses.binary_crossentropy
请参见https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy和https://www.tensorflow.org/api_docs/python/tf/keras/losses/binary_crossentropy
,非常感谢@qmeeus,您向我展示了成功的道路!
我不知道keras.losses.BinaryCrossentropy和keras.losses.binary_crossentropy之间的区别,但这是一个主要问题。
这就是我的做法:
def custom_binary_crossentropy(y_true,y_pred):
"""
Used to reequilibrate the data,as there is more black (0.,articles),than white (255. (recalibrated to 1.),non-articles) on the pages.
"""
# I put 0 so that the shape is (batch_size,256,256)
# and not (batch_size,1)
is_white = y_true[:,:,0]>=0.5
white_error = 1.8*keras.losses.binary_crossentropy(y_true,y_pred)
black_error = keras.losses.binary_crossentropy(y_true,y_pred)
# Returns the right loss for each type of error.
# We do make twice the calculation but I did not find a better way for now
return tf.where(is_white,white_error,black_error)
我不知道tf.where的用法,但是它非常有用。 我在AurélienGéron的精彩著作《使用Keras和TensorFlow进行机器学习》中看到了这本教程。
只需使用next即可:
# Compiling using this function
model.compile(optimizer="rmsprop",loss=custom_binary_crossentropy)
然后使用您的数据和喜欢的超参数来拟合您的模型,您就很好了!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。