KeyError: 'acc' -> acc = history.history['acc']

2 min read 05-10-2024
KeyError: 'acc' -> acc = history.history['acc']


"KeyError: 'acc'" in Keras: Understanding and Fixing the Issue

The Problem:

Many machine learning enthusiasts encounter the dreaded "KeyError: 'acc'" while working with Keras, especially when trying to access training accuracy. This error indicates that the 'acc' key is not present in the history.history dictionary, which usually contains metrics like accuracy, loss, and others.

Scenario and Code:

Let's imagine you've trained a simple Keras model and want to plot the training accuracy. You might write code like this:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras import layers

# Create a simple model
model = Sequential()
model.add(layers.Dense(10, activation='relu', input_shape=(10,)))
model.add(layers.Dense(1, activation='sigmoid'))

# Compile and train the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=10)

# Accessing the accuracy
acc = history.history['acc'] 

# Plotting the accuracy
plt.plot(history.history['acc'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show()

This code will likely throw the "KeyError: 'acc'" error.

Analysis and Clarification:

The error arises because Keras changed its default metric reporting behavior in newer versions. The history.history dictionary no longer contains the 'acc' key. Instead, it uses the key 'accuracy'.

Resolution:

Simply update your code to access the accuracy using the 'accuracy' key:

acc = history.history['accuracy'] 

Additional Insights:

  • Version Check: Ensure you're using a recent Keras version (2.3.0 and above). Older versions might still use 'acc'.
  • Custom Metrics: If you've defined custom metrics, ensure their names are correctly reflected in the history.history dictionary.
  • Multiple Metrics: If you're tracking multiple metrics, check the keys in the history.history dictionary to access the correct values.
  • KeyError in Evaluation: The same error can occur during model evaluation if you attempt to access the accuracy directly. Use model.evaluate(X_test, y_test) and access the metrics through the returned list.

Example:

loss, accuracy = model.evaluate(X_test, y_test)
print('Test Accuracy:', accuracy)

Conclusion:

Understanding the changes in Keras metric reporting is crucial to avoid common errors. This article provides a clear explanation of the "KeyError: 'acc'" and its solution, ensuring a smooth journey for Keras users.

References: