正确绘制混淆矩阵

时间:2021-04-23 07:10:39

标签: python keras deep-learning

import matplotlib.pyplot as plt
from keras.models import load_model


plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

尝试为以下代码片段绘制混淆矩阵时出错

from sklearn.metrics import confusion_matrix
pred = model.predict(X_test)
pred = np.argmax(pred,axis = 1) 
y_true = np.argmax(y_test,axis = 1)

上面代码片段的错误是“NameError: name 'model' is not defined”

CM = confusion_matrix(y_true, pred)
from mlxtend.plotting import plot_confusion_matrix
fig, ax = plot_confusion_matrix(conf_mat=CM ,  figsize=(5, 5))
plt.show()

上述代码段的错误是“NameError: name 'y_true' is not defined”

error image

1 个答案:

答案 0 :(得分:0)

y_true 未定义,因为前一个单元格(发生 model 错误的地方)未完成。当您在发生 y_true 错误的同一单元格中定义 model not defined 时,该单元格不会执行其余的行,因此未定义 y_true

第一个错误发生了 model not defined,因为您没有为变量 model 赋值。这应该首先修复,即:

model = load_model(<filepath to your saved model>)