问题描述:
程序运行出现KeyError: ‘acc’ 和KeyError: 'val_acc’的错误。
解决方法:
在Keras 2.3.0中,矩阵的报告方式已更改为与指定的确切名称相匹配。 如果您使用的是较旧的代码或较旧的代码示例,则可能会遇到错误。 下面是解决方法。
您是否一直在使用Keras的fit()函数返回的“历史记录”对象来绘制或可视化模型的训练历史? 自最近Keras升级以来,您是否一直收到诸如以下的“ KeyError”类型错误,并想知道为什么?
Traceback (most recent call last):
File "lenet_mnist_keras.py", line 163, in <module>
graph_training_history(history)
File "lenet_mnist_keras.py", line 87, in graph_training_history
plt.plot(history.history['acc'])
KeyError: 'acc'
Traceback (most recent call last):
File "lenet_mnist_keras.py", line 163, in <module>
graph_training_history(history)
File "lenet_mnist_keras.py", line 88, in graph_training_history
plt.plot(history.history['val_acc'])
KeyError: 'val_acc'
这是由于Keras 2.3.0版中引入的重大更改所致。
根据2.3.0发行说明:
“Metrics and losses are now reported under the exact name specified by the user (e.g. if you pass metrics=[‘acc’], your metric will be reported under the string “acc”, not “accuracy”, and inversely metrics=[‘accuracy’] will be reported under the string “accuracy”.”
您可以在此处阅读官方发行说明:https://github.com/keras-team/keras/releases/tag/2.3.0
这意味着如果在model.compile()中指定metrics = [“ accuracy”],则历史记录对象将具有键“ accuracy”和“ val_accuracy”。 如果您将其指定为metrics = [“ acc”],则将使用键“ acc”和“ val_acc”来报告它们。
因此,要纠正该错误,您应该在整个代码中使用一种标准。
您可以使用“ acc”,
...
model.compile(loss="categorical_crossentropy",
optimizer=opt, metrics=["acc"])
...
plt.figure(1)
# summarize history for accuracy
plt.subplot(211)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='lower right')
# summarize history for loss
plt.subplot(212)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='upper right')
plt.tight_layout()
plt.show()
或者使用"accuracy"
...
model.compile(loss="categorical_crossentropy",
optimizer=opt, metrics=["accuracy"])
...
plt.figure(1)
# summarize history for accuracy
plt.subplot(211)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='lower right')
# summarize history for loss
plt.subplot(212)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc='upper right')
plt.tight_layout()
plt.show()
只需记住在metrics = […]和您从历史对象访问密钥的地方都使用相同的密钥。
相关链接:https://www.codesofinterest.com/2017/03/graph-model-training-history-keras.html