欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决:KeyError: ‘sparse_categorical_accuracy‘

程序员文章站 2022-03-10 13:27:42
...

解决: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']

大功告成

相关标签: 解决问题锦囊