Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在keras中创建自定义损失函数_Python_Machine Learning_Tensorflow_Keras - Fatal编程技术网

Python 在keras中创建自定义损失函数

Python 在keras中创建自定义损失函数,python,machine-learning,tensorflow,keras,Python,Machine Learning,Tensorflow,Keras,嗨,我一直在尝试在keras中为骰子误差系数制作一个自定义损失函数。它在tensorboard中有它的实现,我尝试在keras中使用tensorflow的相同函数,但当我使用模型时,它不断返回非类型的。在批处理或模型上进行训练。拟合在模型中使用度量时,它会给出适当的值。有人能帮我一下吗?我该怎么办?我曾经尝试过遵循ahundt的Keras FCN这样的库,他使用了自定义丢失函数,但似乎都不起作用。代码中的目标和输出分别是y_true和y_pred,正如keras中loss.py文件中使用的那样

嗨,我一直在尝试在keras中为骰子误差系数制作一个自定义损失函数。它在tensorboard中有它的实现,我尝试在keras中使用tensorflow的相同函数,但当我使用模型时,它不断返回非类型的。在批处理模型上进行训练。拟合在模型中使用度量时,它会给出适当的值。有人能帮我一下吗?我该怎么办?我曾经尝试过遵循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
def dice_hard_coe(目标,输出,阈值=0.5,轴=[1,2],平滑=1e-5):
“参考资料
-----------
-“维基骰子`_
"""
输出=tf.cast(输出>阈值,数据类型=tf.float32)
target=tf.cast(target>threshold,dtype=tf.float32)
inse=tf.减和(tf.乘(输出,目标),轴=轴)
l=tf.减少总和(输出,轴=轴)
r=tf。减少总和(目标,轴=轴)
硬骰子=(2.*插入+平滑)/(l+r+平滑)
硬骰子=tf.减少平均值(硬骰子)
返回硬骰子

在Keras中实现参数化自定义损耗函数有两个步骤。首先,编写系数/度量的方法。第二,编写一个包装器函数,按照Keras所需的方式对内容进行格式化

  • 使用Keras后端而不是直接使用tensorflow来实现DICE等简单的自定义损失函数实际上要干净得多。下面是以这种方式实现的系数示例:

    import keras.backend as K
    def dice_coef(y_true, y_pred, smooth, thresh):
        y_pred = y_pred > thresh
        y_true_f = K.flatten(y_true)
        y_pred_f = K.flatten(y_pred)
        intersection = K.sum(y_true_f * y_pred_f)
    
        return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
    
  • 现在是棘手的部分。Keras损失函数必须仅采用(y_true,y_pred)作为参数。所以我们需要一个单独的函数来返回另一个函数

    def dice_loss(smooth, thresh):
      def dice(y_true, y_pred)
        return -dice_coef(y_true, y_pred, smooth, thresh)
      return dice
    
  • 最后,您可以在Keras编译中使用它,如下所示

    # build model 
    model = my_model()
    # get the loss function
    model_dice = dice_loss(smooth=1e-5, thresh=0.5)
    # compile model
    model.compile(loss=model_dice)
    
    根据,您可以使用如下自定义损耗函数:

    任何带有签名
    loss\u fn(y\u true,y\u pred)
    的可调用函数返回一个损失数组(输入批处理中的一个样本),可以作为损失传递给compile()。请注意,任何此类损失都会自动支持样本加权

    举个简单的例子:

    def my_loss_fn(y_true, y_pred):
        squared_difference = tf.square(y_true - y_pred)
        return tf.reduce_mean(squared_difference, axis=-1)  # Note the `axis=-1`
    
    model.compile(optimizer='adam', loss=my_loss_fn)
    
    import tensorflow as tf
    import numpy as np
    
    def my_loss_fn(y_true, y_pred):
        squared_difference = tf.square(y_true - y_pred)
        return tf.reduce_mean(squared_difference, axis=-1)  # Note the `axis=-1`
    
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(8, activation='relu'),
        tf.keras.layers.Dense(16, activation='relu'),
        tf.keras.layers.Dense(1)])
    
    model.compile(optimizer='adam', loss=my_loss_fn)
    
    x = np.random.rand(1000)
    y = x**2
    
    history = model.fit(x, y, epochs=10)
    
    完整示例:

    def my_loss_fn(y_true, y_pred):
        squared_difference = tf.square(y_true - y_pred)
        return tf.reduce_mean(squared_difference, axis=-1)  # Note the `axis=-1`
    
    model.compile(optimizer='adam', loss=my_loss_fn)
    
    import tensorflow as tf
    import numpy as np
    
    def my_loss_fn(y_true, y_pred):
        squared_difference = tf.square(y_true - y_pred)
        return tf.reduce_mean(squared_difference, axis=-1)  # Note the `axis=-1`
    
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(8, activation='relu'),
        tf.keras.layers.Dense(16, activation='relu'),
        tf.keras.layers.Dense(1)])
    
    model.compile(optimizer='adam', loss=my_loss_fn)
    
    x = np.random.rand(1000)
    y = x**2
    
    history = model.fit(x, y, epochs=10)
    

    “def dice(y_true,y_pred):return-dice_coef(y_true,y_pred,1e-5,0.5)def dice_coef(y_true,y_pred,smooth,thresh):y_pred=K.cast(y_pred>thresh,dtype=tf.float32)y_true=K.flattle(y_true>thresh,dtype=tf.float32)y_true=K.flattle(y_true)y_pred=K(2.*交叉点+平滑)/(K.sum(y_true_f)+K.sum(y_pred_f)+平滑)最终_模型。编译(optimizer=opt,loss=dice,metrics=['acc'])“这给了我一个错误”试图将“x”转换为张量,但失败。错误:不支持任何值。“在将其传递到模型之前是否调用dice实例?
    dice\u fn=dice?”(平滑=1e-5,阈值=0.5)
    最终模型。编译(优化器=opt,损失=dice\u fn)
    它按您所说的方式工作。问题是输出不能按这种方式转换为1,0。因此它返回了一个无值。删除该部分后,它工作得非常好。感谢您的帮助。嗨,这里有人能帮我回答我的问题吗:谢谢,有人能确认这是否有效吗?ypred和ytrue是张量,所以
    ypred=ypred>ytrue
    在我的例子中,任何关于ypred和ytrue的计算都会失败。