我试图在Keras中定义一个自定义指标,该指标考虑了样本权重。拟合模型时,我使用以下样本权重:
training_history = model.fit(
train_data,
train_labels,
sample_weight = train_weights,
epochs = num_epochs,
batch_size = 128,
validation_data = (validation_data, validatation_labels, validation_weights ),
)
我使用的自定义指标的一个示例是AUC(roc曲线下的区域),我将其定义如下:
from keras import backend as K
import tensorflow as tf
def auc(true_labels, predictions, weights = None):
auc = tf.metrics.auc(true_labels, predictions, weights = weights)[1]
K.get_session().run(tf.local_variables_initializer())
return auc
并且我在编译模型时使用以下指标:
model.compile(
optimizer = optimizer,
loss = 'binary_crossentropy',
metrics = ['accuracy', auc]
)
但是据我所知,该度量标准并未考虑样本权重。实际上,我通过比较使用上面定义的自定义指标训练模型时看到的指标值与我自己根据模型输出和样本权重计算得出的指标值进行了比较,这确实产生了截然不同的结果。如何定义上面显示的auc指标以考虑样本权重?
答案 0 :(得分:1)
您可以用另一个以sample_weights
作为参数的函数来包装指标:
def auc(weights):
def metric(true_labels, predictions):
auc = tf.metrics.auc(true_labels, predictions, weights=weights)[1]
K.get_session().run(tf.local_variables_initializer())
return auc
return metric
然后定义一个额外的输入占位符,它将接收样本权重:
sample_weights = Input(shape=(1,))
您的模型可以如下进行编译:
model.compile(
optimizer = optimizer,
loss = 'binary_crossentropy',
metrics = ['accuracy', auc(sample_weights)]
)
注意:未测试。