1

I have been trying to plot my training curve of loss and accuracy using keras in Python script, but I am getting a key error:

Traceback (most recent call last):     
  File "train_mask_detector.py", line 149, in <module>      
  plt.plot(np.arange(0, N), H.history["accuracy"], label="accuracy")     
KeyError: 'accuracy'

The code for training model

opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="binary_crossentropy", optimizer=opt,
    metrics=["accuracy"])

# train the head of the network
H = model.fit(
    aug.flow(trainX, trainY, batch_size=BS),
    steps_per_epoch=len(trainX) // BS,
    validation_data=(testX, testY),
    validation_steps=len(testX) // BS,
    epochs=EPOCHS)


# plot the training loss and accuracy
N = EPOCHS
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, N), H.history["loss"], label="loss")
plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, N), H.history["accuracy"], label="accuracy")
plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_accuracy")

EDIT (after answer): The dictionary keys are

print(H.history.keys()) 
dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])

I changed the plot command to

plt.plot(np.arange(0, N), H.history["acc"], label="accuracy")

but the error persists

KeyError: 'accuracy' 
desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

3

You should check the keys of the dictionary H.history - depending on Keras versions, sometimes the accuracy is returned as acc and sometimes as accuracy:

H.history.keys()

Judging from your error, here it is probably acc; so changing it to

plt.plot(H.history["acc"], label="accuracy")

should probably work (you don't really need the np.arange part for your plots).

Modify similarly your plot command for the validation accuracy, if necessary.

desertnaut
  • 57,590
  • 26
  • 140
  • 166