当前位置: 首页 > 知识库问答 >
问题:

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

贲俊才
2023-03-14

嗨,我一直试图使一个自定义损失函数在kerasdice_error_coefficient。它有它的实现在张量板和我尝试使用相同的函数在keras与张量流但它不断返回一个NoneType当我使用model.train_on_batch或model.fit在那里,因为它给适当的值时,使用在模型中的指标...能不能请人帮帮我我该怎么办?我尝试过跟随像Keras-FCN这样的库,在那里他使用了自定义损失函数,但似乎都不起作用。代码中的目标和输出分别y_true和y_pred在keras的losses.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

共有2个答案

滕星纬
2023-03-14

根据文档,您可以使用如下自定义损耗函数:

任何带有签名loss_fn(y_true,y_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)
颜志业
2023-03-14

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

>

  • 实际上,对于像DICE这样的简单自定义损失函数,使用Keras后端而不直接使用tenstorflow会更干净。下面是这样实现的系数的一个例子:

    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)
    

  •  类似资料:
    • 我需要一些帮助与keras损失函数。我一直在Tensorflow后端的keras上实现自定义损失功能。 我已经在numpy中实现了自定义损失函数,但如果能将其转换为keras损失函数,那就太好了。丢失函数采用数据帧和用户id序列。如果用户id不同,则相同用户id的欧氏距离为正和负。函数返回数据帧的合计标量距离。 我试图实现到keras损失函数。我提取Numpy数组从y_true和y_pred张量对

    • 我手头有一个问题,它优化了一个损失函数,而不是y_pred和y_true的函数。通过Keras留档后,我发现所有自定义损失函数必须是y_pred和y_true的函数。 在Keras中是否有其他方法实现我的损失函数?

    • 我在Tensorflow后端使用Keras。我想创建一个自定义损失函数,它将获得两个直方图之间的欧几里德距离,但我得到了以下错误: TypeError:“Mul”Op的输入“y”的类型float32与参数“x”的类型int32不匹配。 因此,我不知道如何定义我的损失函数。 我试图修改代码,但我得到另一个错误。“h_true=tf.cast(h_true,dtype=tf.dtypes.float3

    • 我有一个NN,它有两个相同的CNN(类似于暹罗网络),然后合并输出,并打算在合并的输出上应用自定义损失函数,如下所示: 在我的自定义损失函数中,我需要将y垂直分解为两块,然后对每一块应用分类交叉熵损失。但是,我不断从我的损失函数得到dtype错误,例如: ()中的ValueError回溯(最近一次调用)---- /usr/local/lib/python3。5/地区包/KERA/发动机/培训。编译

    • 我试图在Keras中构造一个自定义损失函数-这是用于生存分析中的删失数据。 这种损失函数本质上是二元交叉熵,即多标签分类,但是损失函数中的求和项需要根据Y_true标签的可用性而变化。见下面的例子: 示例1:Y_可用的所有标签均为True Y_true=[0,0,0,1,1] Y_pred=[0.1,0.2,0.2,0.8,0.7] 损失=-1/5(log(0.9)log(0.8)log(0.8)

    • 我正在尝试使用Keras创建自定义损失函数。我想根据输入计算损失函数并预测神经网络的输出。 我尝试在Keras中使用自定义loss函数。我认为y_true是我们为训练提供的输出,y_pred是神经网络的预测输出。下面的损失函数与 Keras 中的“mean_squared_error”损失相同。 我想使用神经网络的输入也计算自定义损失函数除了mean_squared_error损失。有没有办法将输