首页 > 解决方案 > 如何创建加权交叉熵损失?

问题描述

我必须处理高度不平衡的数据。据我了解,我需要使用加权交叉熵损失。

我试过这个:

import tensorflow as tf

weights = np.array([<values>])
def loss(y_true, y_pred):
    # weights.shape = (63,)
    # y_true.shape = (64, 63)
    # y_pred.shape = (64, 63)
    return tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(y_true, y_pred, weights))

model.compile('adam', loss=loss, metrics=['acc'])

但是有一个错误:

ValueError: Creating variables on a non-first call to a function decorated with tf.function

我怎样才能创造这种损失?

标签: pythontensorflowkerasloss-functioncross-entropy

解决方案


我建议首先使用class_weightKeras。

class_weight

是一本字典{label:weight}

例如,如果标签 1 中的示例比标签 0 中的示例多 20 倍,那么您可以编写

# Assign 20 times more weight to label 0
model.fit(..., class_weight = {0:20, 1:0})

通过这种方式,您无需担心自己实施加权 CCE。

附加说明:在您的使用中model.compile()不要忘记使用weighted_metrics=['accuracy'],以便有相关反映您的准确性。

model.fit(..., class_weight = {0:20, 1:0}, weighted_metrics = ['accuracy'])

推荐阅读