简体   繁体   English

多输出 keras model 带有监控两个指标的回调

[英]multi-output keras model with a callback that monitors two metrics

I have a tf model that has two outputs, as indicated by this model.compile():我有一个 tf model 有两个输出,如 model.compile() 所示:

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=7e-4), 
              loss={"BV": tf.keras.losses.MeanAbsoluteError(), "Rsp": tf.keras.losses.MeanAbsoluteError()},
              metrics={"BV": [tf.keras.metrics.RootMeanSquaredError(name="RMSE"), tfa.metrics.r_square.RSquare(name="R2")], 
                       "Rsp": [tf.keras.metrics.RootMeanSquaredError(name="RMSE"), tfa.metrics.r_square.RSquare(name="R2")]})

I would like to use the ModelCheckpoint callback, which should monitor a sum of val_BV_R2 and val_Rsp_R2.我想使用 ModelCheckpoint 回调,它应该监控 val_BV_R2 和 val_Rsp_R2 的总和。 I am able to run the callback like this:我可以像这样运行回调:

save_best_model = tf.keras.callbacks.ModelCheckpoint("xyz.hdf5", monitor="val_Rsp_R2")

However, I don't know how to make it to save the model with the highest sum of two metrics.但是,我不知道如何使用两个指标的最高和来保存 model。

According to the tf.keras.callbacks.ModelCheckpoint documentation, the metric to monitor che be only one at a time.根据tf.keras.callbacks.ModelCheckpoint文档, monitor的指标一次只有一个。

One way to achieve what you want, could be to define an additional custom metric, that performs the sum of the two metrics.实现您想要的一种方法可能是定义一个额外的自定义指标,它执行两个指标的总和。 Then you could monitor your custom metric and save the checkpoints as you are already doing.然后,您可以监控您的自定义指标并保存检查点,就像您已经在做的那样。 However this is a bit complicated, due to having multiple outputs.然而,由于有多个输出,这有点复杂。

Alternatively you could define a custom callback that does the same combining.或者,您可以定义一个执行相同组合的自定义回调。 Below a simple example of this second option.下面是第二个选项的一个简单示例。 It should work (sorry I can't test it right now):它应该可以工作(抱歉,我现在无法测试):

class CombineCallback(tf.keras.callbacks.Callback):

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

    def on_epoch_end(self, epoch, logs={}):
        logs['combine_metric'] = 0.5*logs['val_BV_R2'] + 0.5*logs['val_Rsp_R2'] 
        

Inside the callback you should be able to access your metrics directly with logs['name_of_my_metric'] or through the get function logs.get("name_of_my_metric") .在回调中,您应该能够直接使用logs['name_of_my_metric']或通过 get function logs.get("name_of_my_metric")访问您的指标。 Also I multiplied by 0.5 to leave the combined metric approximately in the same range, but see if this works for your case.此外,我乘以0.5以使组合指标大致保持在相同的范围内,但看看这是否适用于您的情况。

To use it just do:要使用它,只需执行以下操作:

save_best_model = CombineCallback("xyz.hdf5")
model.fit(..., callbacks=[save_best_model])

More information can be found at the Examples of Keras callback applications .更多信息可以在Keras 回调应用程序示例中找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM