Convolutional Neural Net-Keras-val_acc Keyerror 'acc'

In a not-so-common case (as I expected after some tensorflow updates), despite choosing metrics=["accuracy"] in the model definitions, I still got the same error.

The solution was: replacing metrics=["acc"] with metrics=["accuracy"] everywhere. In my case, I was unable to plot the parameters of the history of my training. I had to replace

acc = history.history['acc']
val_acc = history.history['val_acc']

loss = history.history['loss']
val_loss = history.history['val_loss']

to

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

Your log variable will be consistent with the metrics when you compile your model.

For example, the following code

model.compile(loss="mean_squared_error", optimizer=optimizer) 
model.fit_generator(gen,epochs=50,callbacks=ModelCheckpoint("model_{acc}.hdf5")])

will gives a KeyError: 'acc' because you didn't set metrics=["accuracy"] in model.compile.

This error also happens when metrics are not matched. For example

model.compile(loss="mean_squared_error",optimizer=optimizer, metrics="binary_accuracy"]) 
model.fit_generator(gen,epochs=50,callbacks=ModelCheckpoint("model_{acc}.hdf5")])

still gives a KeyError: 'acc' because you set a binary_accuracy metric but asking for accuracy later.

If you change the above code to

model.compile(loss="mean_squared_error",optimizer=optimizer, metrics="binary_accuracy"]) 
model.fit_generator(gen,epochs=50,callbacks=ModelCheckpoint("model_{binary_accuracy}.hdf5")])

it will work.

Tags:

Python

Keras