【问题标题】:Custom Keras metric, changing自定义 Keras 指标,不断变化
【发布时间】:2024-11-28 21:10:02
【问题描述】:

我目前正在尝试为 Keras 创建自己的损失函数(使用 Tensorflow 后端)。这是一个简单的分类交叉熵,但我在第一列应用了一个因子来惩罚第一类的更多损失。 然而,我是 Keras 的新手,我不知道如何翻译我的函数(如下),因为我必须使用符号表达式,而且我似乎无法按元素进行:

def custom_categorical_crossentropy(y_true, y_pred):
    y_pred = np.clip(y_pred, _EPSILON, 1.0-_EPSILON)
    out = np.zeros(y_true.shape).astype('float32')
    for i in range(0,y_true.shape[0]):
        for j in range (0,y_true.shape[1]):
            #penalize more all elements on class 1 so that loss takes its low proportion in the dataset into account
            if(j==0):
                out[i][j] = -(prop_database*(y_true[i][j] * np.log(y_pred[i][j]) + (1.0 - y_true[i][j]) * np.log(1.0 - y_pred[i][j])))
            else:
                out[i][j] = -(y_true[i][j] * np.log(y_pred[i][j]) + (1.0 - y_true[i][j]) * np.log(1.0 - y_pred[i][j]))
        out = np.mean(out.astype('float32'), axis=-1)
        return tf.convert_to_tensor(out,
                     dtype=tf.float32,
                     name='custom_loss')

有人可以帮我吗?

非常感谢!

【问题讨论】:

    标签: tensorflow computer-vision keras metrics


    【解决方案1】:

    您可以在fit 方法中使用class_weight 来惩罚类而不创建函数:

    weights = {
                0:2,
                1:1,
                2:1,
                3:1,
                ...
              }
    
    
    model.compile(optimizer=chooseOne, loss='categorical_crossentropy')
    model.fit(......., class_weight = weights)
    

    这将使第一堂课的重要性是其他堂课的两倍。

    【讨论】: