如何用python将混淆矩阵的子图设置为矩形

时间: 2024-02-09 18:11:25 浏览: 26
要将混淆矩阵的子图设置为矩形,可以使用Python中的Matplotlib库。具体步骤如下: 1.导入Matplotlib库和混淆矩阵库 ```python import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix ``` 2.生成混淆矩阵数据 ```python y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_pred = [0, 0, 2, 0, 1, 1, 1, 2, 2] cm = confusion_matrix(y_true, y_pred) ``` 3.绘制混淆矩阵热力图 ```python fig, ax = plt.subplots(figsize=(6, 6)) im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) ``` 4.添加坐标轴标签和标题 ```python ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=class_names, yticklabels=class_names, title=title, ylabel='True label', xlabel='Predicted label') ``` 5.将矩形设置为子图的形状 ```python plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], 'd'), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return ax ``` 这样就可以将混淆矩阵的子图设置为矩形了。完整的代码如下: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data # classes = classes[unique_labels(y_true, y_pred)] classes = classes if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] fig, ax = plt.subplots(figsize=(6, 6)) im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return ax # Example usage class_names = ['class 0', 'class 1', 'class 2'] y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_pred = [0, 0, 2, 0, 1, 1, 1, 2, 2] plot_confusion_matrix(y_true, y_pred, classes=class_names, title='Confusion matrix, without normalization') plt.show() ```

相关推荐

最新推荐

recommend-type

利用python中的matplotlib打印混淆矩阵实例

主要介绍了利用python中的matplotlib打印混淆矩阵实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python sklearn包——混淆矩阵、分类报告等自动生成方式

今天小编就为大家分享一篇python sklearn包——混淆矩阵、分类报告等自动生成方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python读取图像矩阵文件并转换为向量实例

主要介绍了python读取图像矩阵文件并转换为向量实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

深度学习自学记录(3)——两种多分类混淆矩阵的Python实现(含代码)

深度学习自学记录(3)——两种多分类混淆矩阵的Python实现(含代码)1、什么是混淆矩阵2、分类模型评价指标3、两种多分类混淆矩阵3.1直接打印出每一个类别的分类准确率。3.2打印具体的分类结果的数值4、总结 1、...
recommend-type

python矩阵转换为一维数组的实例

今天小编就为大家分享一篇python矩阵转换为一维数组的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】增量式PID的simulink仿真实现

# 2.1 Simulink仿真环境简介 Simulink是MATLAB中用于建模、仿真和分析动态系统的图形化环境。它提供了一个直观的用户界面,允许用户使用块和连接线来创建系统模型。Simulink模型由以下元素组成: - **子系统:**将复杂系统分解成更小的、可管理的模块。 - **块:**代表系统中的组件,如传感器、执行器和控制器。 - **连接线:**表示信号在块之间的流动。 Simulink仿真环境提供了广泛的块库,涵盖了各种工程学科,包括控制系统、电子和机械工程。它还支持用户自定义块的创建,以满足特定仿真需求。 # 2. Simulink仿真环境的搭建和建模 ### 2.
recommend-type

训练集和测试集的准确率都99%,但是预测效果不好

即使训练集和测试集的准确率都很高,但是在实际的预测中表现不佳,可能会有以下几个原因: 1. 数据质量问题:模型训练和测试的数据可能存在问题,比如数据标签错误、数据集采样不均衡、数据集中存在异常值等问题,这些问题可能会导致模型在实际预测中表现不佳。 2. 特征工程问题:模型的特征工程可能存在问题,导致模型无法很好地捕捉数据的特征,从而影响预测效果。 3. 模型选择问题:模型的选择可能不合适,比如选择的模型太简单,无法很好地拟合数据,或者选择的模型太复杂,导致过拟合等问题。 4. 超参数调整问题:模型的超参数可能没有调整到最佳状态,需要进行调整。 针对以上可能的原因,可以采取相应的措施进
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。