绘制混淆矩阵

from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt

c=confusion_matrix(y_true,y_pred,labels=['1','2'])
sns.heatmap(c,cmp='Bluels',annot=True,fmt='.2f)
plt.show()

confusion_matrix()函数计算混淆矩阵,输入分别是真实标签值,预测标签值,labels可以自己设计,也可以默认。

注意:标签值是一维数组。

sns.heatmap()绘制热力图。cmp是颜色,有很多种颜色可以选择。annot=True表示在方框中显示数字,fmt可以设置数字的格式,保留小数点几位。还有ax可以设置文字属性等,这部分可以参考链接2

最后记得用plt.show()显示。

参考链接:

混淆矩阵-confusion_matrix(),注意链接第一个例子答案有问题

sns.heatmap详解

### 使用 mmpretrain 和 Matplotlib 绘制混淆矩阵 尽管 `mmpretrain` 是一个用于预训练模型推理和微调的库,但它本身并不直接提供绘制混淆矩阵的功能。然而,可以通过结合 `mmpretrain` 的预测功能与 Python 中常用的绘图工具(如 `matplotlib` 或 `seaborn`),实现混淆矩阵的可视化。 以下是完整的解决方案: #### 1. 安装依赖项 为了运行以下代码,需确保已安装必要的库。如果尚未安装 `mmpretrain` 和其他依赖项,请按照以下命令操作: ```bash pip install mmpretrain matplotlib seaborn ``` 或者,如果有 Git 工具可用,则推荐通过源码安装以获取最新版本[^2]: ```bash git clone https://github.com/open-mmlab/mmpretrain.git cd mmpretrain pip install -e . ``` #### 2. 加载数据并生成预测结果 假设已经有一个分类任务的数据集以及对应的标签列表。下面是一个简单的例子,展示如何加载模型并对测试集进行预测。 ```python from mmengine import Config from mmpretrain.apis import init_model, inference_model # 初始化配置文件路径、权重文件路径及设备设置 config_file = 'path/to/config.py' # 替换为实际配置文件路径 checkpoint_file = 'path/to/checkpoint.pth' # 替换为实际权重文件路径 device = 'cuda:0' # 加载模型 model = init_model(Config.fromfile(config_file), checkpoint=checkpoint_file, device=device) # 假设 test_data 是包含图像路径及其真实标签的列表 [(img_path, label)] test_data = [ ('image1.jpg', 0), ('image2.jpg', 1), ('image3.jpg', 2), ] predictions = [] true_labels = [] for img_path, true_label in test_data: result = inference_model(model, img_path) predicted_class = int(result['pred_label'].item()) # 获取预测类别索引 predictions.append(predicted_class) true_labels.append(true_label) ``` #### 3. 计算混淆矩阵 利用 Scikit-learn 库计算混淆矩阵。 ```python from sklearn.metrics import confusion_matrix cm = confusion_matrix(true_labels, predictions) print("Confusion Matrix:") print(cm) ``` #### 4. 可视化混淆矩阵 使用 Matplotlib 和 Seaborn 来绘制混淆矩阵。 ```python import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') plt.title('Confusion Matrix Visualization') plt.xlabel('Predicted Labels') plt.ylabel('True Labels') plt.show() ``` 以上代码实现了从加载模型到生成预测结果,再到计算并绘制混淆矩阵的完整流程。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值