机器学习之ROC曲线以及混淆矩阵

本文详细介绍了混淆矩阵的概念及其在机器学习中的应用。混淆矩阵是一种评估分类器性能的重要工具,通过对比真实分类与预测分类来衡量分类准确率。文章还提供了如何使用Python的scikit-learn库计算混淆矩阵的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.ROC曲线

占坑。

-------------------------------------------   分割线  -------------------------------------------

2.混淆矩阵

混淆矩阵的作用对机器学习的学习效果进行评估的一种指标。confusion matrix is to evaluate the accuracy of a classification.它的作用是评估分类的准确度。

混淆矩阵的定义:对于混淆矩阵C,C(i,j) 表示真实分类是第i类,但是预测值为第j类的观测总数。

对于二分类问题(假设1是正类):

C(0,0)表示真反类  TN(true negative)C(0,1)表示假正类  FP(false negative)
C(1,0)表示假反类  FP(false negative)C(1,1)表示真正类  TP(true positive)

混淆矩阵的实现:

    通过使用scikit-learn模块计算混淆矩阵,

  sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None).

    下面对参数进行说明:(注:表格中的数组类型在python中对应为列表list()类型)  



Parameters:

参数:

y_true : 长度为n_samples的数组类型

              表示真实分类。Ground truth (correct) target values.

y_pred : 长度为n_samples的数组类型

               表示由分类器对n个样例的预测分类值。Estimated targets as returned by a classifier.

labels :   [可选参数],长度为n_classes的数组类型 (n_classes表示类别/标签个数)

               这个参数是标签的列表形式,影响输出的混淆矩阵C的行列表示的含义,先输出哪一类的值

                 该矩阵可能被用于重排或者选择其中一个子集计算混淆矩阵。 

              如果不给这个参数(即为None),那么 y_true or y_pred中至少出现一次的值将被用于排列顺序

                 注:1. 混淆矩阵的列表示类别的顺序   2. y_true or y_pred中出现的值就表示类标签

               List of labels to index the matrix. This may be used to reorder or select a subset of labels. 

               If none is given, those that appear at least once in y_true or y_pred are used in sorted order.

sample_weight : 类似长度为n_samples的数组形式,可选参数。

                             样例的权重向量。Sample weights.

Returns:

返回值:

C : array, shape = [n_classes, n_classes]


返回混淆矩阵(Confusion matrix)C,shape=(n_classes, n_classes)。

混淆矩阵的性质:

        矩阵的对角线表示正确分类的个数,非对角线的点是分类错误的情况。


混淆矩阵的实例:

1.计算混淆矩阵:

from sklearn.metrics import confusion_matrix
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
confusion_matrix(y_true, y_pred)

2.使用matplotlib.pyplot画出混淆矩阵:

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`.
    """
    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, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')


plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names,
                      title='Confusion matrix, without normalization')


# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
                      title='Normalized confusion matrix')
plt.show()


-----end-----



### 混淆矩阵ROC曲线的区别、联系及其使用方法 #### 区别 混淆矩阵ROC曲线机器学习模型评估中有不同的侧重点。 1. **粒度与概述** - 混淆矩阵提供的是逐类细分的模型性能分析,能够帮助识别模型在哪一类上表现不佳[^2]。 - ROC曲线则给出整体概览,展示模型在整个阈值范围内的判别能力,并通过AUC(曲线下面积)量化总体性能。 2. **数据集不平衡的影响** - 对于类别不平衡的数据集,混淆矩阵中的精确率和召回率等指标能更直观反映问题所在。 - 而ROC曲线由于未直接考虑类别比例,在这种情况下可能会显得不够敏感。 3. **适用场景** - 混淆矩阵适用于二分类以及多分类任务,可针对每种类别单独评价其预测效果。 - ROC曲线主要用于二分类情境下研究不同决策边界带来的影响;不过也可以推广至多分类情形。 4. **阈值依赖性** - 混淆矩阵基于单一固定的判定标准来计算各项统计量。 - ROC曲线描绘了随着阈值变化时真阳性率(TPR)相对于假阳性率(FPR)的变化趋势[^3]。 #### 联系 两者均用于衡量分类器的表现质量,且存在一定的关联: - 构建ROC曲线的基础正是来自多个混淆矩阵的结果集合。具体而言,每一个特定阈值对应的TPR和FPR可以从相应的混淆矩阵中提取出来形成该点坐标[^3]。 - AUC作为综合考量整个操作空间效能的重要参数之一,实际上是对一系列离散化后的局部区域求积分得到总覆盖面积的过程,这些局部即是由各个独立测试所得出的不同状态下的混淆表贡献而成。 #### 使用方法 以下是两种工具的具体应用指南: ##### 混淆矩阵 - 计算各类别的真正例(True Positive),假正例(False Positive),真反例(True Negative),假反例(False Negative)[^5]。 - 进一步衍生出准确率(Accuracy),精准度(Precision),召回率(Recall/Sensitivity),特异度(Specificity)等一系列关键绩效指示符(KPIs)[^4]。 ##### ROC曲线 - 设定多种可能性判断界限P∈[0,1],分别记录每次试验产生的实际观测值对{(FP_rate_i , TP_rate_i)}并绘制成图象表示形式。 - 利用数值积分技术估算总面积大小以获得最终评分结果——AUC得分越高表明系统越优秀。 ```python from sklearn.metrics import confusion_matrix, roc_curve, auc import matplotlib.pyplot as plt import numpy as np # Example data generation (replace with your actual dataset) y_true = np.array([0, 0, 1, 1]) y_scores = np.array([0.1, 0.4, 0.35, 0.8]) # Confusion Matrix Calculation at default threshold of 0.5 cm_default_threshold = confusion_matrix(y_true, y_scores >= 0.5) fpr, tpr, thresholds = roc_curve(y_true, y_scores) roc_auc = auc(fpr, tpr) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label=f'ROC curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') # Diagonal line representing random guessing. plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic Curve') plt.legend(loc="lower right") plt.show() print("Confusion matrix:\n", cm_default_threshold) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值