How to resolve KeyError: 'val_mean_absolute_error' Keras 2.3.1 and TensorFlow 2.0 From Chollet Deep Learning with Python

How to resolve KeyError: 'val_mean_absolute_error' Keras 2.3.1 and TensorFlow 2.0 From Chollet Deep Learning with Python

我正在阅读 Chollet 的《深度学习与 Python 一书的第 3.7 节。 该项目旨在找出 1970 年代特定波士顿郊区的房屋中位价。

https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/3.7-predicting-house-prices.ipynb

在 "Validating our approach using K-fold validation" 部分,我尝试 运行 此代码块:

num_epochs = 500
all_mae_histories = []
for i in range(k):
    print('processing fold #', i)
    # Prepare the validation data: data from partition # k
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]

    # Prepare the training data: data from all other partitions
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
         train_data[(i + 1) * num_val_samples:]],
        axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
         train_targets[(i + 1) * num_val_samples:]],
        axis=0)

    # Build the Keras model (already compiled)
    model = build_model()
    # Train the model (in silent mode, verbose=0)
    history = model.fit(partial_train_data, partial_train_targets,
                        validation_data=(val_data, val_targets),
                        epochs=num_epochs, batch_size=1, verbose=0)
    mae_history = history.history['val_mean_absolute_error']
    all_mae_histories.append(mae_history)

我收到错误 KeyError: 'val_mean_absolute_error'

mae_history = history.history['val_mean_absolute_error']

我猜解决方案是找出正确的参数来替换 val_mean_absolute_error。我已经尝试查看一些 Keras 文档以了解什么是正确的键值。有人知道正确的键值吗?

你的代码中的问题是,当你编译你的模型时,你没有添加特定的“mae”指标。

如果您想在代码中添加“mae”指标,您需要这样做:

  1. model.compile('sgd', metrics=[tf.keras.metrics.MeanAbsoluteError()])
  2. model.compile('sgd', metrics=['mean_absolute_error'])

完成这一步后,您可以尝试查看正确的名称是val_mean_absolute_error还是val_mae。最有可能的是,如果您像我在选项 2 中演示的那样编译您的模型,您的代码将使用“val_mean_absolute_error”。

此外,您还应该将代码片段放在编译模型的位置,上面的问题文本中缺少它(即 build_model() 函数)

我用“val_mae”替换了“val_mean_absolute_error”,它对我有用

我通过下面的代码行更新它:

   mae_history = history.history["mae"]

仅供参考,即使按照答案中的描述更改行 history.history['val_mae'] 后,我仍然遇到同样的问题。

在我的例子中,为了让 val_mae dict 对象出现在 history.history 对象中,我需要确保 model.fit() 代码包含 'validation_data = (val_data, val_targets)' 参数。我最初忽略了这样做。

History 对象应包含与您编译的对象相同的名称。 例如:
mean_absolute_error 给出 val_mean_absolute_error
mae 给出 val_mae
accuracy 给出 val_accuracy
acc 给出 val_acc