添加自定义指标Keras子类化API

问题描述 投票:0回答:1

[我遵循“使用Scikit-Learn,Keras和TensorFlow进行动手学习的机器学习,第二版-AurélienGeron”第12章的“基于模型内部的损失和度量”一节,其中他展示了如何添加不依赖标签和预测的自定义损失和指标。

为了说明这一点,我们通过在上部隐藏层之上添加一个层来添加自定义“重构损失”,该层应再现输入。损失是重建损失和输入之间的均方差。

他显示了添加自定义损失的代码,效果很好,但是即使按照他的描述,我也无法添加度量,因为它会引发“ ValueError”。他说:]]

同样,您可以通过以下方式基于模型内部添加自定义指标:只要结果是a的输出,就可以用您想要的任何方式进行计算指标对象。例如,您可以创建一个keras.metrics.Mean对象在构造函数中,然后在call()方法中调用它,并将其传递给recon_loss,最后通过调用模型的add_metric()方法。

这是代码(我为自己添加的行添加了#MINE)

import tensorflow as tf
from tensorflow import keras
class ReconstructingRegressor(keras.models.Model):
    def __init__(self, output_dim, **kwargs):
        super().__init__(**kwargs)
        self.hidden = [keras.layers.Dense(30, activation="selu",
                                          kernel_initializer="lecun_normal")
                       for _ in range(5)]
        self.out = keras.layers.Dense(output_dim)
        self.reconstruction_mean = keras.metrics.Mean(name="reconstruction_error") #MINE

    def build(self, batch_input_shape):
        n_inputs = batch_input_shape[-1]
        self.reconstruct = keras.layers.Dense(n_inputs)
        super().build(batch_input_shape)

    def call(self, inputs, training=None):
        Z = inputs
        for layer in self.hidden:
            Z = layer(Z)
        reconstruction = self.reconstruct(Z)
        recon_loss = tf.reduce_mean(tf.square(reconstruction - inputs))
        self.add_loss(0.05 * recon_loss)
        if training:                                      #MINE
            result = self.reconstruction_mean(recon_loss) #MINE
        else:                                             #MINE
            result = 0.                                   #MINE, I have also tried different things here, 
                                                          #but the help showed a similar sample to this.
        self.add_metric(result, name="foo")               #MINE
        return self.out(Z)

然后编译并拟合模型:

training_set_size=10
X_dummy = np.random.randn(training_set_size, 8) 
y_dummy = np.random.randn(training_set_size, 1)

model = ReconstructingRegressor(1)
model.compile(loss="mse", optimizer="nadam")
history = model.fit(X_dummy, y_dummy, epochs=2)

哪个抛出:


ValueError: in converted code:

    <ipython-input-296-878bdeb30546>:26 call  *
        self.add_metric(result, name="foo")               #MINE
    C:\Users\Kique\Anaconda3\envs\piz3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py:1147 add_metric
        self._symbolic_add_metric(value, aggregation, name)
    C:\Users\Kique\Anaconda3\envs\piz3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py:1867 _symbolic_add_metric
        'We do not support adding an aggregated metric result tensor that '

    ValueError: We do not support adding an aggregated metric result tensor that is not the output of a `tf.keras.metrics.Metric` metric instance. Without having access to the metric instance we cannot reset the state of a metric after every epoch during training. You can create a `tf.keras.metrics.Metric` instance and pass the result here or pass an un-aggregated result with `aggregation` parameter set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs), name='mean_activation', aggregation='mean')`

已经读过,我尝试了类似的方法来解决该问题,但这只是导致了不同的错误。我该如何解决?什么是“正确”的方法?

我在Windows上使用conda,并已安装tensorflow-gpu 2.1.0。

[我遵循“使用Scikit-Learn,Keras和TensorFlow进行动手机器学习,第二版-AurélienGeron”第12章的“基于模型内部的损失和度量”,在其中...

tensorflow keras deep-learning keras-layer tf.keras
1个回答
0
投票

问题就在这里:

© www.soinside.com 2019 - 2024. All rights reserved.