python - 加入 Keras 中每个输出的指标(在多个输出中)

标签 python tensorflow keras multipleoutputs keras-tuner

我正在 Keras 中研究多输出模型。我已经实现了两个自定义指标 auroc 和 auprc,它们被传递到 compile Keras模型的方法:

def auc(y_true, y_pred, curve='PR'):
    score, up_opt = tf.compat.v1.metrics.auc(y_true, y_pred, curve=curve, summation_method="careful_interpolation")
    K.get_session().run(tf.local_variables_initializer())
    with tf.control_dependencies([up_opt]):
        score = tf.identity(score)
    return score

def auprc(y_true, y_pred):
    return auc(y_true, y_pred, curve='PR')

def auroc(y_true, y_pred):
    return auc(y_true, y_pred, curve='ROC')

mlp_model.compile(loss=...,
                    optimizer=...,
                    metrics=[auprc, auroc])

使用这种方法,我获得了每个输出的 auprc/auroc 值,但是,为了使用贝叶斯优化器优化我的超参数,我需要一个单一的指标(例如:每个输出的 auprc 的平均值或总和)。我不知道如何将我的指标合并为一个指标。

编辑:这里是所需结果的示例

现在,对于每个时期,都会打印以下指标:
out1_auprc: 0.0267 - out2_auprc: 0.0277 - out3_auprc: 0.0294

哪里out1 , out2 , out3是我的神经网络输出,我希望获得类似的东西:
average_auprc: 0.0279 - out1_auprc: 0.0267 - out2_auprc: 0.0277 - out3_auprc: 0.0294

我正在使用 Keras Tuner 进行贝叶斯优化。

任何帮助表示赞赏,谢谢。

最佳答案

我覆盖了创建自定义回调的问题

class MergeMetrics(Callback):

    def __init__(self,**kargs):
        super(MergeMetrics,self).__init__(**kargs)

    def on_epoch_begin(self,epoch, logs={}):
        return

    def on_epoch_end(self, epoch, logs={}):
        logs['merge_metrics'] = 0.5*logs["y1_mse"]+0.5*logs["y2_mse"]

我使用这个回调来合并来自 2 个不同输出的 2 个指标。例如,我使用了一个简单的问题,但您可以轻松地将其集成到您的问题中,并将其与验证集集成

这是虚拟示例
X = np.random.uniform(0,1, (1000,10))
y1 = np.random.uniform(0,1, 1000)
y2 = np.random.uniform(0,1, 1000)


inp = Input((10))
x = Dense(32, activation='relu')(inp)
out1 = Dense(1, name='y1')(x)
out2 = Dense(1, name='y2')(x)
m = Model(inp, [out1,out2])
m.compile('adam','mae', metrics='mse')


checkpoint = MergeMetrics()
m.fit(X, [y1,y2], epochs=10, callbacks=[checkpoint])

打印输出
loss: ..... y1_mse: 0.0863 - y2_mse: 0.0875 - merge_metrics: 0.0869

关于python - 加入 Keras 中每个输出的指标(在多个输出中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61959143/

相关文章:

python - 绘制前 10 名与所有其他值的对比图

python - 如何将字符串列表写入文件并添加换行符?

tensorflow - TensorFlow BasicLSTMCell 实现中的 'call' 和 '__call__' 有什么区别?

python - 凯拉斯属性错误: 'list' object has no attribute 'ndim'

python - 训练基于 BERT 的模型会导致 OutOfMemory 错误。我该如何解决?

python - 在构建和训练 3D Keras U-NET 时出现 ValueError

python - Matthews 相关系数与 Keras

python - sphinx 中方法组的文档字符串

Python 多处理不能很好地与 uuid.uuid4() 配合使用

tensorflow - TFRecords/TensorFlow 服务 : Converting TFRecords into (GRPC or RESTFul) TensorFlow Serving requests?