赞
踩
之前就了解过混淆矩阵,但是一直没有实践,今天刚好有数据实践一下,这里记录一下代码实现过程,方便以后查阅。
关于混淆矩阵,在这篇博客也提到过:机器学习|模型评估——AUC
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, labels_name, title, colorbar=False, cmap=None):
plt.imshow(cm, interpolation='nearest', cmap=cmap) # 在特定的窗口上显示图像
for i in range(len(cm)):
for j in range(len(cm)):
plt.annotate(cm[j, i], xy=(i, j), horizontalalignment='center', verticalalignment='center')
if colorbar:
plt.colorbar()
num_local = np.array(range(len(labels_name)))
plt.xticks(num_local, labels_name) # 将标签印在x轴坐标上
plt.yticks(num_local, labels_name) # 将标签印在y轴坐标上
plt.title(title) # 图像标题
plt.ylabel('True label')
plt.xlabel('Predicted label')
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
cm = confusion_matrix(y_true, y_pred)
print(cm)
plot_confusion_matrix(cm, ["ant", "bird", "cat"], "Confusion Matrix")
from sklearn.metrics import confusion_matrix
from sklearn.metrics import ConfusionMatrixDisplay
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
ConfusionMatrixDisplay.from_predictions(y_true, y_pred, display_labels=["ant", "bird", "cat"], cmap=plt.cm.Reds, colorbar=True)
plt.title("Confusion Matrix")
Python中生成并绘制混淆矩阵(confusion matrix)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。