绘制混淆矩阵热力图


import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def plot_confusion_matrix(pred_index, targets, labels, save_file, show_number=100):
    sns.set()
    
    y_true = targets
    y_pred = pred_index
    C2= confusion_matrix(y_pred, y_true, labels=labels)
    print("C2.shape", C2.shape) #打印出来看看
    has_targets = np.sum(C2, axis=0)
    has_targets = np.where(has_targets > 0)[0]
    has_preds = np.sum(C2, axis=1)
    has_preds = np.where(has_preds > 0)[0]
    C = C2[:, has_targets]
    C = C[has_preds, :]
    
    x_ticks = [i+0.5 for i in range(has_targets.shape[0])]
    x_labels= has_targets.tolist()
    
    y_ticks = [i+0.5 for i in range(has_preds.shape[0])]
    y_labels=has_preds.tolist()
    
    # import pdb; pdb.set_trace()
    f,ax=plt.subplots(1, 1,  figsize=(8+len(x_labels)//2, 6+len(y_labels)//2))
    print("real shape:", len(x_labels), len(y_labels))
    
    colors = [(0, "white"),(0.1, 'green'), (0.5, "yellow"), (1, "red"), ]
    cmap = mcolors.LinearSegmentedColormap.from_list('custom_colormap', colors)
    sns.heatmap(C, annot=True, annot_kws={"size": 10, 'weight':'bold'}, ax=ax, cmap=cmap, fmt=".0f", linewidths=0, cbar=True) #画热力图
    # sns.heatmap(C, annot=True, annot_kws={"size": 10, 'weight':'bold'}, ax=ax, cmap=plt.cm.Blues, fmt=".0f", linewidths=0, cbar=True) #画热力图
    # sns.heatmap(C3, linewidths = 0.01, annot=True, ax=ax) #画热力图
    ax.set_title('confusion matrix') #标题
    ax.set_xlabel('true') #x轴
    ax.set_xticks(ticks=x_ticks, labels=x_labels)
    ax.set_ylabel('predict') #y轴
    ax.set_yticks(ticks=y_ticks, labels=y_labels)
    
    print("generate finished") #打印出来看看
    plt.savefig(save_file, format='png')
    print("save png finished") #打印出来看看
    # import pdb; pdb.set_trace()


save_file = out_file_path.replace(".pkl", ".png")
plot_confusion_matrix(pred_indexs, targets, [i for i in range(class_number)], save_file)
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NineDays66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值