绘制混淆矩阵和训练情况的代码

文章介绍了如何在Python中使用matplotlib和seaborn库绘制混淆矩阵,并展示如何读取和处理CSV数据来显示训练和验证损失的动态变化,包括平滑曲线。
摘要由CSDN通过智能技术生成

根据结果绘制混淆矩阵confusion matrix和training/valid loss的python代码

混淆矩阵部分:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import matplotlib

# 字体设置(中文)
matplotlib.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
matplotlib.rcParams['font.size'] = 14
matplotlib.rcParams['axes.unicode_minus'] = False  # 正确显示负号

# 混淆矩阵csv的路径
data_path = "./confusion_matrix.csv"

confusion_matrix_data = pd.read_csv(data_path)
confusion_matrix_data.head()

confusion_matrix = confusion_matrix_data.set_index(confusion_matrix_data.columns[0])
labels = confusion_matrix.columns

plt.figure(figsize=(10, 8))
sns.heatmap(confusion_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=labels, yticklabels=labels)
plt.title('混淆矩阵')
plt.xlabel('预测值')
plt.ylabel('真实值')
plt.show()

使用前,把预测结果的csv放在同级目录即可;如下:

在这里插入图片描述
结果:
在这里插入图片描述
训练和验证损失部分:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

# 字体设置(中文)
matplotlib.rcParams['font.family'] = 'SimHei'  # 设置字体为黑体
matplotlib.rcParams['font.size'] = 14
matplotlib.rcParams['axes.unicode_minus'] = False  # 正确显示负号

epoch_loss_path = "./epoch_loss.txt"
epoch_val_loss_path = "./epoch_val_loss.txt"
epoch_miou_path = "./epoch_miou.txt"

epoch_loss = np.loadtxt(epoch_loss_path)
epoch_val_loss = np.loadtxt(epoch_val_loss_path)
epoch_miou = np.loadtxt(epoch_miou_path)

def smooth(values, weight=0.6):
    smoothed_values = []
    last = values[0]
    for point in values:
        smoothed_val = last * weight + (1 - weight) * point
        smoothed_values.append(smoothed_val)
        last = smoothed_val
    return np.array(smoothed_values)

smoothed_loss = smooth(epoch_loss)
smoothed_val_loss = smooth(epoch_val_loss)

plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1)
plt.plot(epoch_loss, label='训练损失', color='blue')
plt.plot(epoch_val_loss, label='验证损失', color='red')
plt.plot(smoothed_val_loss, label='平滑-验证损失', color='green', linestyle='--')
plt.plot(smoothed_loss, label='平滑-训练损失', color='orange', linestyle='--')
plt.title('训练-验证损失')
plt.xlabel('训练轮次')
plt.ylabel('损失值')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(epoch_miou, label='mIoU', color='purple')
plt.title('平均交并比')
plt.xlabel('训练轮次')
plt.ylabel('平均交并比')
plt.legend()

plt.tight_layout()
plt.show()

同样的,把数据放在同级目录下,.txt档;如下:
不是这图片怎么缩小啊这么个图占这么大片地方
… … 总之,valid loss 和指标(题中是mIOU,可根据需求自行修改)也和图中training loss 一致即可;
运行结果如下:
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值