我想绘制我训练模型的混淆矩阵,但当我试图绘制我的混淆矩阵时卡住了。没有。当预测值和实际值的样本长度相同时,两个参数的长度相同,但仍然抛出误差
TypeError: plot_confusion_matrix()缺少1个必需的位置参数:'y_true'
这里是我的代码供参考
# downloading VGG16 model
img_height, img_width = 224,224
conv_base = vgg16.VGG16(weights='imagenet', include_top=False, pooling='max', input_shape = (img_width, img_height, 3))
# creating a model without freezing the layers of Model
model = models.Sequential()
model.add(conv_base)
model.add(layers.Dense(nb_categories, activation='softmax'))
model.summary()
learning_rate = 5e-5
epochs = 3
checkpoint = ModelCheckpoint("sign_classifier.h5", monitor = 'val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)
model.compile(loss="categorical_crossentropy", optimizer=tensorflow.optimizers.Adam(lr=learning_rate, clipnorm = 1.), metrics = ['acc'])
history = model.fit_generator(train_generator,
epochs=epochs,
shuffle=True,
validation_data=val_generator,
callbacks=[checkpoint]
)
Y_pred = model.predict_generator(test_generator)
y_pred = np.argmax(Y_pred, axis=1)
print("test data samples",len(test_generator.classes))
print("predicted data samples",len(y_pred))
print("Shape of Predicted Value",y_pred.shape)
print("Shape of actual Value",test_generator.classes.shape)
y_true = test_generator.classes
cm = confusion_matrix(test_generator.classes, y_pred)
print("Confusion Matrix",cm)
plot_confusion_matrix(y_true, y_pred, labels = category_names, normalize=False)
以上代码的输出为
test data samples 47
predicted data samples 47
Shape of Predicted Value (47,)
Shape of actual Value (47,)
Confusion Matrix [[22 0 1]
[ 0 9 0]
[13 0 2]]
sklearn.metrics。plot_confe_matrix需要3个位置参数classifier
,X
,y_true
。所以你需要传递你的模型作为分类器参数。
但是,如果您将模型作为参数传递给函数,则会出现另一个问题,您的模型将不会被识别为分类器。为了解决这个问题,我创建了一个笔记本,可能会帮助你。这里是链接
使用以下格式:
plot_confusion_matrix(X =test_generator.classes, y_true = y_pred, labels = category_names, normalize=False)