大家好,今天聊聊
机器学习模型评估指标
~
这方面在前期,很多人不太注意,其实是非常重要的一块内容。
机器学习模型评估指标的重要性体现在它们提供了客观、可量化的方式来衡量模型性能,帮助选择最适合的模型和调整参数;
它们是优化模型、改进算法和指导业务决策的关键依据;合适的评估指标能够有效地反映模型在不同方面的表现,从而指导进一步改进和优化。
咱们今天介绍11种模型评估指标,案例都比较相似,大家可以学习起来~
ROC 曲线和 AUC
均方误差(Mean Squared Error,MSE)
平均绝对误差(Mean Absolute Error,MAE)
交叉验证分数(Cross-Validation Score)
准确率
准确率(Accuracy)是机器学习和数据分类任务中常用的评估指标之一,用于衡量模型在整个数据集上的预测准确程度。它是指模型正确分类的样本数量与总样本数量之比。
准确率是一个简单直观的指标,通常用于评估模型的整体性能。它可以通过以下公式计算:
其中:
是真正例 (True Positives),即模型将正类别样本正确地预测为正类别的数量。
是真负例 (True Negatives),即模型将负类别样本正确地预测为负类别的数量。
是假正例 (False Positives),即模型将负类别样本错误地预测为正类别的数量。
是假负例 (False Negatives),即模型将正类别样本错误地预测为负类别的数量。
基本原理
准确率是将预测正确的样本数量与总样本数量之比,它衡量的是模型在整个数据集上的表现。然而,当数据集不平衡(即某一类样本数量明显多于其他类别)时,准确率可能不是一个很好的评估指标,因为即使模型预测所有样本都属于多数类别,也能获得相对较高的准确率。
核心点
在处理不平衡数据时,准确率可能不是一个很好的指标。
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, confusion_matrix# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2
, random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算准确率 accuracy = accuracy_score(y_test, y_pred) print("Accuracy:" , accuracy)# 绘制混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) print("Confusion Matrix:" ) print(conf_matrix)# 绘制评估指标 plt.imshow(conf_matrix, cmap='binary' , interpolation='None' ) plt.colorbar() plt.xticks([0 , 1 ]) plt.yticks([0 , 1 ]) plt.xlabel('Predicted Label' ) plt.ylabel('True Label' ) plt.title('Confusion Matrix' ) plt.show()
使用逻辑回归模型进行训练,并计算了模型的准确率。
然后,它绘制了混淆矩阵,可视化了模型的预测结果。
精确率
精确率(Precision)是机器学习和数据分类任务中常用的评估指标之一,用于衡量模型在预测为正类别的样本中,真正为正类别的样本所占的比例。精确率用于解决以下问题:在所有预测为正类别的样本中,有多少是真正的正类别。
精确率是指在所有被分类为正类别的样本中,正确分类为正类别的样本所占的比例。它可以通过以下公式计算:
其中:
是真正例 (True Positives),即模型将正类别样本正确地预测为正类别的数量。
是假正例 (False Positives),即模型将负类别样本错误地预测为正类别的数量。
基本原理
精确率的核心思想是衡量模型在所有预测为正类别的样本中,真正为正类别的样本所占的比例。这个指标对于那些需要准确识别正例的任务尤为重要,比如医学诊断中的疾病检测。高精确率表示模型在识别正例方面有很好的表现。
核心点
精确率用于衡量模型在所有预测为正类别的样本中,真正为正类别的样本所占的比例。
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import precision_score, confusion_matrix# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算精确率 precision = precision_score(y_test, y_pred) print("Precision:" , precision)# 绘制混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) print("Confusion Matrix:" ) print(conf_matrix)# 绘制评估指标 plt.imshow(conf_matrix, cmap='binary' , interpolation='None' ) plt.colorbar() plt.xticks([0 , 1 ]) plt.yticks([0 , 1 ]) plt.xlabel('Predicted Label' ) plt.ylabel('True Label' ) plt.title('Confusion Matrix' ) plt.show()
同样使用逻辑回归模型进行训练,并计算了模型的精确率。然后,它绘制了混淆矩阵,可视化了模型的预测结果。
召回率
召回率(Recall),也称为灵敏度(Sensitivity)或真正例率(True Positive Rate),是机器学习和数据分类任务中常用的评估指标之一,用于衡量模型在所有真正为正类别的样本中,成功预测为正类别的比例。召回率用于解决以下问题:在所有实际为正类别的样本中,有多少被成功预测为正类别。
召回率是指在所有实际为正类别的样本中,成功预测为正类别的比例。它可以通过以下公式计算:
其中:
是真正例 (True Positives),即模型将正类别样本正确地预测为正类别的数量。
是假负例 (False Negatives),即模型将正类别样本错误地预测为负类别的数量。
基本原理
召回率的核心思想是衡量模型在识别正例方面的表现。它强调了模型对于实际为正类别的样本的识别能力,对于那些需要尽量避免漏诊的任务,比如疾病检测,召回率是一个非常重要的评估指标。
核心点
召回率用于衡量模型在所有实际为正类别的样本中,成功预测为正类别的比例。
对于需要尽量避免漏诊的任务,如疾病检测,召回率是一个非常重要的评估指标。
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import recall_score, confusion_matrix# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算召回率 recall = recall_score(y_test, y_pred) print("Recall:" , recall)# 绘制混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) print("Confusion Matrix:" ) print(conf_matrix)# 绘制评估指标 plt.imshow(conf_matrix, cmap='binary' , interpolation='None' ) plt.colorbar() plt.xticks([0 , 1 ]) plt.yticks([0 , 1 ]) plt.xlabel('Predicted Label' ) plt.ylabel('True Label' ) plt.title('Confusion Matrix' ) plt.show()
使用逻辑回归模型进行训练,并计算了模型的召回率。
F1 分数
F1分数(F1-Score)是机器学习和数据分类任务中常用的综合评估指标,它同时考虑了模型的精确率(Precision)和召回率(Recall)。F1分数是精确率和召回率的调和平均值,用于衡量模型在正类别的识别和预测方面的综合表现。
F1分数是精确率和召回率的调和平均值,用于综合评估模型在正类别识别和预测方面的表现。可以通过以下公式计算:
基本原理
F1分数综合考虑了模型的精确率和召回率,因此可以在一定程度上弥补精确率和召回率单独使用时的不足。F1分数越高,表示模型在识别和预测正类别方面的综合表现越好。
核心点
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import f1_score, confusion_matrix# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算F1分数 f1 = f1_score(y_test, y_pred) print("F1 Score:" , f1)# 绘制混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) print("Confusion Matrix:" ) print(conf_matrix)# 绘制评估指标 plt.imshow(conf_matrix, cmap='binary' , interpolation='None' ) plt.colorbar() plt.xticks([0 , 1 ]) plt.yticks([0 , 1 ]) plt.xlabel('Predicted Label' ) plt.ylabel('True Label' ) plt.title('Confusion Matrix' ) plt.show()
同样使用逻辑回归模型进行训练,并计算了模型的F1分数。然后,它绘制了混淆矩阵,可视化了模型的预测结果。
ROC 曲线和 AUC
ROC曲线(Receiver Operating Characteristic Curve)和AUC(Area Under Curve)是用于评估二分类模型性能的重要工具,它们基于真正例率(True Positive Rate,召回率)和假正例率(False Positive Rate)来描述模型在不同阈值下的性能表现。
ROC曲线是一种绘制真正例率(TPR)随着假正例率(FPR)变化的图形。在ROC曲线上,横轴表示FPR,纵轴表示TPR。AUC是ROC曲线下的面积,用于量化分类器的性能。AUC的取值范围在0到1之间,一般来说,AUC越大表示分类器性能越好。
基本原理
ROC曲线基于真正例率和假正例率,它展示了在不同分类阈值下,模型在识别正例和负例方面的性能。ROC曲线上的点越靠近左上角,表示模型性能越好。AUC是ROC曲线下的面积,它等于ROC曲线与横轴之间的面积,可以用来比较不同模型的性能,AUC越大表示模型性能越好。
核心点
是真正例(True Positives),模型将正类别样本正确地预测为正类别的数量。
是假负例(False Negatives),模型将正类别样本错误地预测为负类别的数量。
是假正例(False Positives),模型将负类别样本错误地预测为正类别的数量。
是真负例(True Negatives),模型将负类别样本正确地预测为负类别的数量。
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_curve, auc# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred_proba = model.predict_proba(X_test)[:, 1 ]# 计算ROC曲线和AUC fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba) roc_auc = auc(fpr, tpr) print("AUC:" , roc_auc)# 绘制ROC曲线 plt.figure() plt.plot(fpr, tpr, color='darkorange' , lw=2 , label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0 , 1 ], [0 , 1 ], color='navy' , lw=2 , linestyle='--' ) plt.xlim([0.0 , 1.0 ]) plt.ylim([0.0 , 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()
使用逻辑回归模型进行训练,并计算了模型的ROC曲线和AUC。然后,它绘制了ROC曲线,并显示了AUC的值。
混淆矩阵
混淆矩阵(Confusion Matrix)是用于评估分类模型性能的一种表格,它以矩阵的形式展示了模型在测试集上的预测结果与实际标签之间的关系。混淆矩阵将真实标签分为正类别和负类别,并将模型的预测结果也分为正类别和负类别,从而可以对模型的分类准确性进行更详细的分析。
混淆矩阵是一个二维数组,其行表示真实标签,列表示模型预测结果。对于二分类问题,混淆矩阵通常是一个2x2的矩阵,包括四个元素:真正例(True Positives,TP)、假正例(False Positives,FP)、真负例(True Negatives,TN)、假负例(False Negatives,FN)。每个元素的含义如下:
基本原理
混淆矩阵用于描述模型在不同类别上的预测结果,帮助评估模型的分类准确性和错误情况。通过混淆矩阵,可以计算出模型的精确率、召回率、F1分数等评估指标,从而更全面地评估模型的性能。
核心点
混淆矩阵以矩阵的形式展示了模型的预测结果与实际标签之间的关系。
通过混淆矩阵,可以计算出模型的精确率、召回率、F1分数等评估指标。
真
正
例
数
量
假
正
例
数
量
真
负
例
数
量
假
负
例
数
量
代码示例
下面是一个使用Python实现的示例代码,该代码演示了如何计算混淆矩阵并绘制评估指标曲线:
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import confusion_matrix# 生成模拟数据集 X, y = make_classification(n_samples=1000 , n_features=20 , n_classes=2 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练逻辑回归模型 model = LogisticRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) print("Confusion Matrix:" ) print(conf_matrix)# 绘制混淆矩阵 plt.imshow(conf_matrix, cmap='binary' , interpolation='None' ) plt.colorbar() plt.xticks([0 , 1 ]) plt.yticks([0 , 1 ]) plt.xlabel('Predicted Label' ) plt.ylabel('True Label' ) plt.title('Confusion Matrix' ) plt.show()
均方误差
均方误差(Mean Squared Error,MSE)是回归任务中常用的评估指标,用于衡量模型预测值与真实值之间的平均偏差的平方。MSE越小表示模型对数据的拟合程度越好。
均方误差是通过计算预测值与真实值之间的差异来评估模型的性能。对于回归任务,MSE是平方损失函数的平均值。它可以通过以下公式计算:
其中:
基本原理
均方误差衡量了模型的预测值与真实值之间的平均偏差的平方。当模型的预测值与真实值之间的偏差较大时,MSE会增大;而当偏差较小时,MSE会减小。因此,MSE越小表示模型对数据的拟合程度越好。
核心点
均方误差用于衡量模型预测值与真实值之间的平均偏差的平方。
代码示例
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import make_regressionfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error# 生成模拟数据集 X, y = make_regression(n_samples=100 , n_features=1 , noise=0.1 , random_state=42 )# 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2 , random_state=42 )# 训练线性回归模型 model = LinearRegression() model.fit(X_train, y_train)# 在测试集上做预测 y_pred = model.predict(X_test)# 计算均方误差 mse = mean_squared_error(y_test, y_pred) print("Mean Squared Error:" , mse)# 绘制评估指标 plt.scatter(X_test, y_test, color='black' , label='Actual' ) plt.plot(X_test, y_pred, color='blue' , linewidth=3 , label='Predicted' ) plt.title('Actual vs Predicted' ) plt.xlabel('X' ) plt.ylabel('y' ) plt.legend() plt.show()
使用线性回归模型进行训练,并计算了模型的均方误差。然后,它绘制了预测值与真实值的散点图,以展示模型的预测效果。
平均绝对误差
平均绝对误差(Mean Absolute Error,MAE)是回归任务中常用的评估指标,用于衡量模型预测值与真实值之间的平均绝对偏差。MAE越小表示模型对数据的拟合程度越好。
平均绝对误差是通过计算预测值与真实值之间的绝对差异来评估模型的性能。对于回归任务,MAE是绝对损失函数的平均值。它可以通过以下公式计算:
其中: