Python利用matplotlib绘制混淆矩阵详解

木白
木白
发布时间:2026-10-14 | 5人浏览过
原创

本文详细介绍如何在Python中使用matplotlib库可视化打印混淆矩阵,涵盖sklearn.metrics.confusion_matrix与tf.confusion_matrix两个核心API的参数解析、对比及完整代码示例,帮助开发者直观评估分类模型性能。

混淆矩阵可视化背景与目的

在前面的讨论中,我们提到混淆矩阵是处理分类问题时至关重要的评估指标。那么,如何更直观地展示这一矩阵呢?直接生成表格或进行前端可视化是常见做法。笔者曾尝试使用前端工具(如D5)进行可视化并截图,但效果并不理想。

具体实现代码如下:


import itertools
import matplotlib.pyplot as plt
import numpy as np
 
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')
 plt.show()
 # plt.savefig('confusion_matrix',dpi=200)
 
cnf_matrix = np.array([
 [4101, 2, 5, 24, 0],
 [50, 3930, 6, 14, 5],
 [29, 3, 3973, 4, 0],
 [45, 7, 1, 3878, 119],
 [31, 1, 8, 28, 3936],
])
 
class_names = ['Buildings', 'Farmland', 'Greenbelt', 'Wasteland', 'Water']
 
# plt.figure()
# plot_confusion_matrix(cnf_matrix, classes=class_names,
#      title='Confusion matrix, without normalization')
 
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
      title='Normalized confusion matrix')

将上述代码放置于合适位置,即可生成混淆矩阵可视化结果。当然,这一步也可以在模型运行过程中直接完成可视化操作。

混淆矩阵原理与定义

补充知识:深入理解混淆矩阵(Confusion matrix)的原理及其在scikit-learn和TensorFlow中的具体应用。

混淆矩阵的基本原理

在机器学习领域,混淆矩阵是一种误差矩阵,常用于以可视化方式评估监督学习算法的性能。该矩阵是一个(n_classes, n_classes)大小的方阵,其中n_classes代表类别的数量。矩阵的每一行表示真实类别的实例,而每一列表示预测类别的实例(这是Tensorflow和scikit-learn采用的实现方式)。另一种定义(如Wikipedia所述)则是每一行表示预测类别的实例,每一列表示真实类别的实例。通过混淆矩阵,可以清晰地看出系统是否容易混淆两个特定的类别,这也是其名称的由来。

混淆矩阵本质上是一种特殊的列联表(contingency table)或交叉制表(cross tabulation/crosstab)。它包含两个维度:真实值("actual")和预测值("predicted"),这两个维度具有相同的类别集合。在列联表中,每个维度和类别的组合构成一个变量,以表格形式可视化地展示多个变量的频率分布。

sklearn与TensorFlow API实现

混淆矩阵的具体使用方法(基于scikit-learn和TensorFlow)

接下来,我们将介绍在scikit-learn和TensorFlow中计算混淆矩阵的API接口函数,并通过一个示例展示这两个API函数的实际使用。

scikit-learn混淆矩阵函数:sklearn.metrics.confusion_matrix API接口


skearn.metrics.confusion_matrix(
 y_true, # array, Gound true (correct) target values
 y_pred, # array, Estimated targets as returned by a classifier
 labels=None, # array, List of labels to index the matrix.
 sample_weight=None # array-like of shape = [n_samples], Optional sample weights
)

在scikit-learn库中,计算混淆矩阵主要用于评估分类任务的准确度。

根据定义,混淆矩阵C中的元素Ci,j等于真实值为组i且预测为组j的观测数量。因此,对于二分类任务,预测结果中正确的负例数(true negatives, TN)对应C0,0;错误的负例数(false negatives, FN)对应C1,0;真实的正例数对应C1,1;错误的正例数对应C0,1。

如果参数labels设置为None,scikit-learn会将出现在y_true或y_pred中的所有值添加到标记列表labels中,并按顺序排列。

TensorFlow混淆矩阵函数:tf.confusion_matrix API接口


tf.confusion_matrix(
 labels, # 1-D Tensor of real labels for the classification task
 predictions, # 1-D Tensor of predictions for a givenclassification
 num_classes=None, # The possible number of labels the classification task can have
 dtype=tf.int32, # Data type of the confusion matrix 
 name=None, # Scope name
 weights=None, # An optional Tensor whose shape matches predictions
)

TensorFlow中tf.confusion_matrix函数的num_classes参数含义与scikit-learn中sklearn.metrics.confusion_matrix的labels参数相近,均是与标记相关的参数,表示类别的总个数,但不列出具体标记值。在TensorFlow中,通常使用整数作为标记;若标记为字符串等非整数类型,需先转换为整数表示。如果num_classes参数为None,则会将labels和predictions中的最大值加1作为num_classes的值。

tf.confusion_matrix的weights参数与sklearn.metrics.confusion_matrix的sample_weight参数含义相同,均用于对预测值进行加权,在此基础上计算混淆矩阵单元的值。

完整代码示例与总结

代码使用示例


#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Author: klchang
Description: 
  A simple example for tf.confusion_matrix and sklearn.metrics.confusion_matrix.
Date: 2018.9.8
"""
from __future__ import print_function
import tensorflow as tf
import sklearn.metrics
 
y_true = [1, 2, 4]
y_pred = [2, 2, 4]
 
# Build graph with tf.confusion_matrix operation
sess = tf.InteractiveSession()
op = tf.confusion_matrix(y_true, y_pred)
op2 = tf.confusion_matrix(y_true, y_pred, num_classes=6, dtype=tf.float32, weights=tf.constant([0.3, 0.4, 0.3]))
# Execute the graph
print ("confusion matrix in tensorflow: ")
print ("1. default: \n", op.eval())
print ("2. customed: \n", sess.run(op2))
sess.close()
 
# Use sklearn.metrics.confusion_matrix function
print ("\nconfusion matrix in scikit-learn: ")
print ("1. default: \n", sklearn.metrics.confusion_matrix(y_true, y_pred))
print ("2. customed: \n", sklearn.metrics.confusion_matrix(y_true, y_pred, labels=range(6), sample_weight=[0.3, 0.4, 0.3]))

以上就是利用Python中的matplotlib打印混淆矩阵的完整实例,希望能为大家提供参考,也欢迎大家继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表