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

我正在尝试应用一个适合我的模型的自定义损失函数。标签是一个形状为(5,)的二进制数组,数组中1的位置很重要。例如[1,0,0,0,0]y_true。如果y_pred[0,0,1,0,0],其损失将高于y_pred[0,0,0,0,1]的情况。

以下是初步的函数代码:

from keras import backend as Kdef tf_loss_function(y_true, y_pred):    y_pred = K.clip(y_pred, _Epsilon, 1.0-_Epsilon)    true = 0    pred = 0    tf_session = K.get_session()    y_true = y_true.eval(tf_session())    y_pred = y_pred.eval(tf_session())    shape = y_true.shape    for row in range(shape[0]):        for elem in range(shape[1]):            true += y_true[elem] * elem            pred += y_true[elem] * elem    return ((true - pred) ** 2)/shape[0]

我知道这个函数完全错误,但基本思路是正确的。我该如何编写一个可以直接用于model.compile()的函数?


回答:

你可能在寻找class_weight,这是你传递给fit的一个参数:

weights = {0:1, 1:2, 2:3, 3:4, 4:5}model.fit(X, Y, ..., class_weight=weights)

如果你仍然想要那个损失函数:

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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

你好,我一直在尝试在Keras中为dice_error_coefficient创建一个自定义损失函数。它在tensorboard中有实现,我尝试在使用TensorFlow的Keras中使用相同的函数,但当我使用model.train_on_batchmodel.fit时,它总是返回一个NoneType,而当在模型的指标中使用时,它会返回正确的值。请问有人能帮助我解决这个问题吗?我尝试过使用ahundt的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

回答:

此外,你可以通过继承现有的损失函数来扩展它。例如,屏蔽BinaryCrossEntropy

class MaskedBinaryCrossentropy(tf.keras.losses.BinaryCrossentropy):    def call(self, y_true, y_pred):        mask = y_true != -1        y_true = y_true[mask]        y_pred = y_pred[mask]        return super().call(y_true, y_pred)

一个好的起点是custom log指南:https://www.tensorflow.org/guide/keras/train_and_evaluate#custom_losses

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注