混淆矩阵代码

混淆矩阵对数据可视化很有用,我在做轴承故障诊断时,也用到了这个混淆矩阵,我在下面贴出来两种代码,供大家使用借鉴,我也是从网上找的改的

# 开发时间:2022/8/4  19:35
#  绘制混淆矩阵
import torch
from matplotlib import pyplot as plt
import numpy as np
import itertools




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`.
    Input
    - cm : 计算出的混淆矩阵的值
    - classes : 混淆矩阵中每一行每一列对应的列
    - normalize : True:显示百分比, False:显示个数
    """
    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, cm[i, j].numpy(),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')


# 计算混淆矩阵
def confusion_matrix(preds, labels, conf_matrix):
    preds = torch.argmax(preds, 1)
    for p, t in zip(preds, labels):
        conf_matrix[t, p] += 1

    return conf_matrix
# 混淆矩阵定义
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.jet):
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks,('good','bad'))
    plt.yticks(tick_marks,('good','bad'))
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, '{:.2f}'.format(cm[i, j]), horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('真实类别')
    plt.xlabel('预测类别')
    plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
    plt.show()
 
# 显示混淆矩阵
def plot_confuse(model, x_val, y_val):
    predictions = model.predict_classes(x_val)
    truelabel = y_val.argmax(axis=-1)   # 将one-hot转化为label
    conf_mat = confusion_matrix(y_true=truelabel, y_pred=predictions)
    plt.figure()
    plot_confusion_matrix(conf_mat, range(np.max(truelabel)+1))

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
knn是一种常见的分类算法,它的混淆矩阵可以通过sklearn.metrics中的confusion_matrix函数进行计算。下面是一个knn混淆矩阵代码实例: 引用中提供了一些算法的import语句,这里我们需要用到其中的KNeighborsClassifier算法。假设我们有一个训练集X_train和对应的标签y_train,还有一个测试集X_test和对应的标签y_test。我们可以将knn算法应用于训练集,然后用其对测试集进行预测,并计算混淆矩阵。具体代码如下: ```python from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix # 假设我们已经有训练集X_train和对应标签y_train,测试集X_test和对应标签y_test # 定义knn分类器,这里假设k=3 knn = KNeighborsClassifier(n_neighbors=3) # 将knn分类器应用于训练集上 knn.fit(X_train, y_train) # 对测试集进行预测 y_pred = knn.predict(X_test) # 计算混淆矩阵 cm = confusion_matrix(y_test, y_pred) print(cm) ``` 上述代码中,我们首先使用KNeighborsClassifier算法定义了一个knn分类器,然后将其应用于训练集上。接下来,我们使用训练好的knn分类器对测试集进行预测,并计算混淆矩阵。最后,我们输出混淆矩阵。 在这段代码中,混淆矩阵被保存在变量cm中,其形式如下: |真实标签\预测标签|正例|负例| |---|---|---| |正例|TP|FN| |负例|FP|TN| 其中TP表示真正例(True Positive),即被正确地预测为正例的样本数;FN表示假负例(False Negative),即被错误地预测为负例的样本数;FP表示假正例(False Positive),即被错误地预测为正例的样本数;TN表示真负例(True Negative),即被正确地预测为负例的样本数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

新池坡南

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

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

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

打赏作者

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

抵扣说明:

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

余额充值