解决:KeyError: ‘sparse_categorical_accuracy’
项目场景:
学习tf2.0,然后想显示acc和loss,然后就写了下面的代码:
history =model.fit_generator(train_generator,
epochs=1,
steps_per_epoch=2276//32, 。
validation_data=validation_generator,
validation_steps=251//32,
callbacks=[cp_callback],
verbose=1 #verbose = 0 为不在标准输出流输出日志信息,1 为输出进度条记录
)
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.subplot(1, 2, 1)
# plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
问题描述:
但是一直报错
acc = history.history['sparse_categorical_accuracy']
KeyError: 'sparse_categorical_accuracy'
原因分析:
然后就把history的字典print了一下,发现:history字典里的是
dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])
解决方案:
将下面的代码
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
改成
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
大功告成