目前:您有 4 个 NumPy 数组:y_test、y_train、y_test_pred 和 y_train_pred。
您想要:2 个 NumPy 数组,y_true 和 y_pred。
您可以将训练 + 测试与 np.concatenate 结合使用。例如:
y_test = np.array([0, 1, 0, 1])
y_train = np.array([0, 0, 1, 1])
y_test_pred = np.array([1, 1, 0, 1]) # from classifier_logistic.predict(x_test)
y_train_pred = np.array([0, 1, 0, 1]) # from classifier_logistic.predict(x_train)
y_true = np.concatenate((y_train, y_test)) # you already have this as `Y`
y_pred = np.concatenate((y_train_pred, y_test_pred))
在 sklearn 文档中有一个 very good example 绘制混淆矩阵。
这是一个考虑到您的案例的示例:
import itertools
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
# Source: http://scikit-learn.org/stable/auto_examples/model_selection/
# plot_confusion_matrix.html#confusion-matrix
y_test = np.array([1, 1, 0, 1])
y_train = np.array([0, 0, 1, 1])
y_test_pred = np.array([1, 1, 0, 1]) # from classifier_logistic.predict(x_test)
y_train_pred = np.array([0, 1, 0, 1]) # from classifier_logistic.predict(x_train)
y_true = np.concatenate((y_train, y_test))
y_pred = np.concatenate((y_train_pred, y_test_pred))
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
cm = confusion_matrix(y_true, y_pred)
np.set_printoptions(precision=2)
plt.figure()
plot_confusion_matrix(cm, classes=[0, 1],
title='Confusion matrix')