【问题标题】:How to monitor a filtered version of a metric in EarlyStopping callback in tensorflow?如何在 tensorflow 的 EarlyStopping 回调中监控指标的过滤版本?
【发布时间】:2021-05-27 10:52:31
【问题描述】:

我一直有这个问题。在训练神经网络时,验证损失可能会很嘈杂(如果您使用诸如 dropout 之类的随机层,有时甚至是训练损失)。当数据集较小时尤其如此。

这使得当使用诸如EarlyStopping 或ReduceLROnPlateau 之类的回调时,这些回调会被过早触发(即使需要很大的耐心)。另外,有时我不想在ReduceLROnPLateau 回调中使用很大的耐心。

解决方案不是直接监控某个指标(例如 val_loss),而是监控该指标的过滤版本(跨时期)(例如 val_loss 的指数移动平均值)。但是,我没有看到任何简单的方法来解决这个问题,因为回调只接受不依赖于先前时​​期的指标。我曾尝试使用自定义训练循环通过自定义过滤指标重现这些回调的功能,但我认为这不是正确的方法。是否有另一种(更简单)的方法来监控回调中损失的过滤版本,而不重新实现回调的整个功能?

编辑:

这就是我所说的监控指标的过滤版本的意思。当前的EarlyStopping 是这样工作的:

best_loss = float('inf')
best_epoch = 0
for epoch in range(n_epochs):
    # ...
    new_loss = # compute loss of current epoch
    if new_loss < best_loss:
        best_loss = new_loss
        best_epoch = epoch
    if epoch - best_epoch > patience:
        break

监控过滤后的指标如下:

best_loss = float('inf')
filtered_loss = 10 # example initial value
best_epoch = 0
for epoch in range(n_epochs):
    # ...
    new_loss = # compute loss of current epoch
    filtered_loss = 0.1*new_loss + 0.9*filtered_loss
    if filtered_loss < best_loss:
        best_loss = filtered_loss
        best_epoch = epoch
    if epoch - best_epoch > patience:
        break

【问题讨论】:

  • 指标的过滤版本是什么意思?
  • 我编辑了帖子
  • 抱歉,您似乎正在调整损失分数。只有吗?
  • 是的,但也可以是其他指标,比如验证损失、R2、准确率……我不想每次想用EarlyStopping或@的时候都写一个自定义的训练循环987654328@ 带过滤器。此外,如果可能的话,最好不要从头开始重写这些回调。这就是我想要实现的目标。

标签: python tensorflow keras


【解决方案1】:

这是解决问题的一种相对简单的方法。您创建了一个自定义tf.keras.metrics.Metric,它具有tf.keras.metrics.Metric 作为属性和一定的内存大小。度量的结果将是内存中值的平均值。您在回调中监控该指标。

class AveragePreviousMetric(tf.keras.metrics.Metric):
    def __init__(self, metric, num_updates, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.num_updates = num_updates
        self.accumulator = tf.Variable(tf.zeros(self.num_updates))
        self.idx = tf.Variable(0)
        self.metric = metric

    def update_state(self, *args, **kwargs):
        self.metric.update_state(*args, **kwargs)

    def reset_states(self, *args, **kwargs):
        # a simple queue with modulo indexing
        update_op = self.accumulator.scatter_update(
            tf.IndexedSlices(self.metric.result(), self.idx % self.num_updates)
        )
        # we just want to be sure to only increase the counter 
        # if the variable has been updated
        with tf.control_dependencies([update_op]):
            self.idx.assign_add(1)
        # we reset the state of the internal metric
        self.metric.reset_states(*args, **kwargs)

    def _result(self):
        return self.metric.result()

    def _filtered_result(self):
        return 0.9 * self.accumulator[: self.idx] + 0.1 * self._result()

    def result(self):
        # if the idx is zero, the accumulator is empty and _filtered_result will yield an error
        return tf.cond(tf.equal(self.idx, 0), self._result, self._filtered_result)

以及如何使用它的简单示例:

m = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
x = tf.random.uniform((100, 1))
y = tf.random.uniform((100, 1))
avg_mse = AveragePreviousMetric(
    tf.keras.metrics.MeanSquaredError(), name="avg_mse", num_updates=5
)
m.compile(loss="mse", metrics=[avg_mse, "mse"], optimizer="sgd")
hist = m.fit(x, y, epochs=5, verbose=2)

当这个例子运行时:

Epoch 1/5
4/4 - 0s - loss: 0.1956 - avg_mse: 0.1956 - mse: 0.1956
Epoch 2/5
4/4 - 0s - loss: 0.1943 - avg_mse: 0.1954 - mse: 0.1943
Epoch 3/5
4/4 - 0s - loss: 0.1932 - avg_mse: 0.1948 - mse: 0.1932
Epoch 4/5
4/4 - 0s - loss: 0.1919 - avg_mse: 0.1941 - mse: 0.1919
Epoch 5/5
4/4 - 0s - loss: 0.1908 - avg_mse: 0.1935 - mse: 0.1908

【讨论】:

  • 谢谢,这是一个非常可重用的代码。但是,我发现了一个问题:在使用训练和验证数据时,状态变量是共享的,因为我在编译模型时只传递了一次度量对象。这使得过滤器给出不正确的结果。我需要为训练和验证创建不同的状态变量吗?
  • 不幸的是,这是该方法的一个限制,因为您没有关于是否在验证数据或训练数据上调用该指标的上下文。
  • 并且没有解决方法可以将此类用于验证指标?
  • 你也许可以使用answer。
  • 感谢您的帮助,我用我正在使用的最终解决方案更新了问题。适用于训练和验证。将它添加到 tensorflow-addons 是否值得?
【解决方案2】:

我会走上编写自定义指标的道路(继承 keras.Metric)。 Keras Metrics 跨批次是有状态的。要使用每个 epoch 平滑,您需要让这个指标引用一组额外的张量,这些张量存储以前的 epoch 结果并手动重置这些值......例如在训练开始之前。然后,您的回调可以按名称引用此指标。

示例实现:

from tensorflow.keras import backend as K

class SmothedMSE(keras.metrics.Metric):
    def __init__(self, **kwargs):
        super().__init__(name='smothed_mse', **kwargs)

        self.history = self.add_weight(name='history', shape=(4,), initializer='zeros')
        self.sum = self.add_weight(name='sum', initializer='zeros')
        self.count = self.add_weight(name='count', initializer='zeros', dtype=tf.int32)

    def clear(self):
        K.set_value(self.history, np.zeros(4))

    def update_state(self, y_true, y_pred, sample_weight=None):
        x = keras.metrics.mse(y_true, y_pred)
        self.sum.assign_add(tf.reduce_sum(x, axis=-1))
        self.count.assign_add(tf.shape(x)[0])

    def result(self):
        h = tf.reduce_sum(self.history)
        nhistory = tf.roll(self.history, shift=1, axis=0)
        x = tf.divide(self.sum, tf.cast(self.count, tf.float32))
        nhistory = tf.tensor_scatter_nd_update(nhistory, [[0]], tf.expand_dims(x, 0))
        self.history.assign(nhistory)
        return (x + h) / 2.
    
    def reset_state(self):
        K.set_value(self.sum, 0.)
        K.set_value(self.count, 0)

更多详情请访问: https://colab.research.google.com/drive/1K1a1fovqqs-ARbD_BVnhnYlrMqvk4cCo?usp=sharing

【讨论】:

  • 谢谢,这似乎是我想要的,但我真的不知道如何创建一个在 epoch 之间调用的方法 reset_state() 之后不重置的状态变量。 reset_state() 如何选择重置哪些变量?
  • 添加了一个使用 4 值历史记录的示例...您必须显式调用方法 clear() 来重置历史记录,以防您想要多次调用 fit() 而无需重新编译模型。
  • 感谢您的帮助,我用我正在使用的解决方案更新了问题。
【解决方案3】:

我经常遇到这个问题,所以我写了一个自定义回调,最初监控训练准确性并根据它调整学习率。这避免了验证损失最初可能发生根本变化的问题,我有一个称为“阈值”的参数。一旦训练准确度超过阈值,回调就会切换到监控验证损失,并据此调整学习率。在训练结束时,回调也总是将模型的权重设置为损失最低的时期的权重。这段代码在这里提供很长。但是要了解如何编写自定义回调,文档是 here.

【讨论】:

  • 那么这是唯一的方法吗?我期望不要重新实现监控某个指标的每个回调。
  • 可能还有其他方法,但我不知道。
【解决方案4】:

感谢@Pedro Marques 和@lescurel 的贡献,我设法创建了一个度量类,它可以平滑跨时代的任何其他度量。由于使用了不同的状态变量,它也能够在训练期间使用验证集时工作。

有一个管理状态逻辑的基类:

class SmoothMetric(tf.keras.metrics.Metric):
    def __init__(self, metric, name=None, **kwargs):
        if name is None:
            name = 'smooth_' + metric.name
        super().__init__(name=name, **kwargs)
        self.metric = metric
        self.in_test_step = tf.Variable(False)
        self.prev_in_test_step = tf.Variable(False)
        self.train_states = {}
        self.test_states = {}

    def add_state_variable(self, name, **kwargs):
        self.train_states[name] = tf.Variable(**kwargs)
        self.test_states[name] = tf.Variable(**kwargs)

    def get_state_variable(self, name):
        return tf.cond(self.in_test_step, lambda: self.test_states[name], lambda: self.train_states[name])

    def update_state(self, *args, **kwargs):
        self.metric.update_state(*args, **kwargs)
        self.prev_in_test_step.assign(self.in_test_step)

    def update_filter_state_prevoius_epoch(self):
        raise NotImplementedError('Needs to be overwritten')

    def reset_state(self, *args, **kwargs):
        # update state of the previous mode
        tmp = self.in_test_step.read_value()
        self.in_test_step.assign(self.prev_in_test_step)
        self.update_filter_state_prevoius_epoch()
        self.in_test_step.assign(tmp)
        self.metric.reset_state(*args, **kwargs)

然后,我定义了一个继承自前一个的类,它实现了过滤器。在这种情况下,它实现了指数移动平均线,但也可以制作其他过滤器,例如简单移动平均线。

class SmoothMetricEMA(SmoothMetric):
    def __init__(self, metric, alpha=0.1, name=None, **kwargs) -> None:
        super().__init__(metric=metric, name=name, **kwargs)
        self.alpha = alpha
        self.add_state_variable('accum', initial_value=0.0)
        self.add_state_variable('idx', initial_value=0)

    def update_filter_state_prevoius_epoch(self):
        self.get_state_variable('accum').assign(self.result())
        self.get_state_variable('idx').assign_add(1)

    def _result(self):
        return self.metric.result()

    def _filtered_result(self):
        return (1 - self.alpha) * self.get_state_variable('accum') + self.alpha * self._result()

    def result(self):
        # if the idx is zero, the accumulator is 0 and _filtered_result will not give the correct result
        return tf.cond(tf.equal(self.get_state_variable('idx'), 0), self._result, self._filtered_result)

这里是 SMA 过滤器替代方案:

class SmoothMetricSMA(SmoothMetric):
    def __init__(self, metric, n_samples=10, remove_outliers=None, name=None, **kwargs) -> None:
        super().__init__(metric=metric, name=name, **kwargs)
        self.queue_size = n_samples - 1
        self.remove_outliers = remove_outliers
        self.add_state_variable('accum', initial_value=tf.zeros(self.queue_size))
        self.add_state_variable('idx', initial_value=0)

    def update_filter_state_prevoius_epoch(self):
        self.get_state_variable('accum').scatter_update(
            tf.IndexedSlices(self.metric.result(), self.get_state_variable('idx') % self.queue_size))
        self.get_state_variable('idx').assign_add(1)

    def _result(self):
        return self.metric.result()

    def _filtered_result(self):
        queue = tf.concat([self.get_state_variable('accum')[:self.get_state_variable('idx')], tf.reshape(self._result(), (1,))], axis=0)
        if self.remove_outliers is not None:
            queue = tf.sort(queue)
            eff_size = tf.cast(tf.minimum(self.get_state_variable('idx')+1, self.queue_size), tf.float32)
            queue = queue[tf.cast(tf.math.floor(eff_size*self.remove_outliers/2), tf.int32):tf.cast(tf.math.ceil(eff_size*(1-self.remove_outliers/2)), tf.int32)]
        return tf.reduce_mean(queue)

    def result(self):
        # if the idx is zero, the accumulator is 0 and _filtered_result will not give the correct result
        return tf.cond(tf.equal(self.get_state_variable('idx'), 0), self._result, self._filtered_result)

最后,要使过滤器工作,必须使用以下回调。这告诉过滤器它是处于训练模式还是测试模式。

class NotifySmoothMetricsCallback(tf.keras.callbacks.Callback):
    """
    Notifies the smooth metric if it is on train or test step.
    """
    def on_test_begin(self, logs):
        for metric in self.model.metrics:
            if isinstance(metric, SmoothMetric):
                metric.in_test_step.assign(True)
    def on_test_end(self,  logs):
        for metric in self.model.metrics:
            if isinstance(metric, SmoothMetric):
                metric.in_test_step.assign(False)

    def on_epoch_begin(self, epoch, logs):
        for metric in self.model.metrics:
            if isinstance(metric, SmoothMetric):
                metric.in_test_step.assign(False)
    def on_epoch_end(self, epoch, logs):
        for metric in self.model.metrics:
            if isinstance(metric, SmoothMetric):
                metric.in_test_step.assign(False)
    def on_train_begin(self, logs):
        for metric in self.model.metrics:
            if isinstance(metric, SmoothMetric):
                metric.in_test_step.assign(False)

以下是如何使用这些类的示例:

metrics=[
    SmoothMetricEMA(tf.metrics.MeanSquaredError(), alpha=0.1, name='smooth'),
]
callbacks = [
    tf.keras.callbacks.EarlyStopping(monitor='val_smooth', patience=10, verbose=1),
    NotifySmoothMetricsCallback(),
]
model.compile(optimizer='adam', loss='mse', metrics=metrics)

model.fit(x_train, y_train, batch_size=32, epochs=100,
    validation_data=(x_val, y_val),
    callbacks=callbacks,
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 2020-08-16
    • 2021-12-02
    • 2020-08-29
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多