如何让Keras只计算验证数据的某个指标?

qnzebej0  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(153)

我将tf.keras与TensorFlow 1.14.0配合使用。我实施了一个自定义指标,该指标计算量很大,如果只是将其添加到model.compile(..., metrics=[...])提供的指标列表中,会减慢训练过程。
如何让Keras在训练迭代期间跳过度量的计算,但在每个时期结束时在验证数据上计算(并打印)?

aydmsdu9

aydmsdu91#

要做到这一点,您可以在度量计算中创建一个tf.variable,它确定计算是否继续,然后在测试运行时使用回调更新它。

class MyCustomMetric(tf.keras.metrics.Metrics):

    def __init__(self, **kwargs):
        # Initialise as normal and add flag variable for when to run computation
        super(MyCustomMetric, self).__init__(**kwargs)
        self.metric_variable = self.add_weight(name='metric_varaible', initializer='zeros')
        self.on = tf.Variable(False)

    def update_state(self, y_true, y_pred, sample_weight=None):
        # Use conditional to determine if computation is done
        if self.on:
            # run computation
            self.metric_variable.assign_add(computation_result)

    def result(self):
        return self.metric_variable

    def reset_states(self):
        self.metric_variable.assign(0.)

class ToggleMetrics(tf.keras.callbacks.Callback):
    '''On test begin (i.e. when evaluate() is called or 
     validation data is run during fit()) toggle metric flag '''
    def on_test_begin(self, logs):
        for metric in self.model.metrics:
            if 'MyCustomMetric' in metric.name:
                metric.on.assign(True)
    def on_test_end(self,  logs):
        for metric in self.model.metrics:
            if 'MyCustomMetric' in metric.name:
                metric.on.assign(False)

相关问题