Datawhale 动手学数据分析Task5 模型搭建和评估

第三章 模型搭建和评估–建模

经过前面的两章的知识点的学习,我可以对数数据的本身进行处理,比如数据本身的增删查补,还可以做必要的清洗工作。那么下面我们就要开始使用我们前面处理好的数据了。这一章我们要做的就是使用数据,我们做数据分析的目的也就是,运用我们的数据以及结合我的业务来得到某些我们需要知道的结果。那么分析的第一步就是建模,搭建一个预测模型或者其他模型;我们从这个模型的到结果之后,我们要分析我的模型是不是足够的可靠,那我就需要评估这个模型。今天我们学习建模,下一节我们学习评估。

我们拥有的泰坦尼克号的数据集,那么我们这次的目的就是,完成泰坦尼克号存活预测这个任务。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import Image
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.figsize'] = (10, 6)  # 设置输出图片大小

载入这些库,如果缺少某些库,请安装他们

【思考】这些库的作用是什么呢?你需要查一查

#思考题回答
答:1)pandas的作用:数据文件读取/文本数据读取、索引、选取和数据过滤、算法运算和数据对齐、函数的应用和映射、重置索引。
2)numpy的作用:数组的算数和逻辑运算、傅立叶变换和用于图形操作的例程、与线性代数有关的操作。
3)matplotlib的作用:是用来生成绘图,直方图,功率谱,条形图,错误图,散点图等。
4)seaborn的作用:seaborn是python中的一个非常强大的数据可视化库。它高度集成了matplotlib,所以代码量比matplotlib小很多,有时候一行代码即可。
5)IPython.display的作用:用于显示对象,如图片等。

%matplotlib inline

载入我们提供清洗之后的数据(clear_data.csv),大家也将原始数据载入(train.csv),说说他们有什么不同

# 读取原始数据
train = pd.read_csv('train.csv')
train.shape
(891, 12)
train.head()
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
0103Braund, Mr. Owen Harrismale22.010A/5 211717.2500NaNS
1211Cumings, Mrs. John Bradley (Florence Briggs Th...female38.010PC 1759971.2833C85C
2313Heikkinen, Miss. Lainafemale26.000STON/O2. 31012827.9250NaNS
3411Futrelle, Mrs. Jacques Heath (Lily May Peel)female35.01011380353.1000C123S
4503Allen, Mr. William Henrymale35.0003734508.0500NaNS
# 读取清洗数据
clear = pd.read_csv('clear_data.csv')
clear.shape
(891, 11)
clear.head()
PassengerIdPclassAgeSibSpParchFareSex_femaleSex_maleEmbarked_CEmbarked_QEmbarked_S
00322.0107.250001001
11138.01071.283310100
22326.0007.925010001
33135.01053.100010001
44335.0008.050001001

答:train.csv包含了Survived人是否存活,Name,Ticket(票号),Cabin。而clear.csv却没有这些,Name和Ticket的去除估计是为了脱敏,Sex和Embarked是利用one-hot表示法。

模型搭建

  • 处理完前面的数据我们就得到建模数据,下一步是选择合适模型
  • 在进行模型选择之前我们需要先知道数据集最终是进行监督学习还是无监督学习
  • 模型的选择一方面是通过我们的任务来决定的。
  • 除了根据我们任务来选择模型外,还可以根据数据样本量以及特征的稀疏性来决定
  • 刚开始我们总是先尝试使用一个基本的模型来作为其baseline,进而再训练其他模型做对比,最终选择泛化能力或性能比较好的模型

这里我的建模,并不是从零开始,自己一个人完成完成所有代码的编译。我们这里使用一个机器学习最常用的一个库(sklearn)来完成我们的模型的搭建

下面给出sklearn的算法选择路径,供大家参考

# sklearn模型算法选择路径图
Image('sklearn.png')

在这里插入图片描述

【思考】数据集哪些差异会导致模型在拟合数据是发生变化

答:数据的样本量、数据的特征数、类别数目是否已知、文本数据还是数值数据、是否为带标记的数据、是分类问题还是数量预测问题、是为了观察还是其他任务。

任务一:切割训练集和测试集

这里使用留出法划分数据集

  • 将数据集分为自变量和因变量
  • 按比例切割训练集和测试集(一般测试集的比例有30%、25%、20%、15%和10%)
  • 使用分层抽样
  • 设置随机种子以便结果能复现

【思考】

  • 划分数据集的方法有哪些?
  • 为什么使用分层抽样,这样的好处有什么?

1.答:留出法、交叉验证法、自助法。

2.答:分层抽样就是在划分的时候要尽可能保证数据分布的一致性,即避免因数据划分过程引入额外的偏差而对最终结果产生影响。

任务提示1
  • 切割数据集是为了后续能评估模型泛化能力
  • sklearn中切割数据集的方法为train_test_split
  • 查看函数文档可以在jupyter notebook里面使用train_test_split?后回车即可看到
  • 分层和随机种子在参数里寻找

要从clear_data.csv和train.csv中提取train_test_split()所需的参数

from sklearn.model_selection import train_test_split
# 一般先取出X和y后再切割,有些情况会使用到未切割的,这时候X和y就可以用,x是清洗好的数据,y是我们要预测的存活数据'Survived'
# train_size和test_size为None,则将设置test_size为0.25。即训练集:测试集=3:1
X = clear
y = train['Survived']
# 对数据集进行切割
# stratify是为了保持split前类的分布。分层抽样
# eg:用了stratify参数,training集和testing集的类的比例是 A:B= 4:1,等同于split前的比例(80:20)。通常在这种类分布不平衡的情况下会用到stratify。
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=47)
# 查看数据形状
X_train.shape, X_test.shape
((668, 11), (223, 11))

【思考】

  • 什么情况下切割数据集的时候不用进行随机选取

答:随机抽取的本质是通过随机选取的样本来代表总体,这样样本具有随机性、代表性。如果本身数据集就足够随机或已经预先经过随机处理的话,那就没有必要在切割数据集的时候进行随机选取。

任务二:模型创建
  • 创建基于线性模型的分类模型(逻辑回归)
  • 创建基于树的分类模型(决策树、随机森林)
  • 分别使用这些模型进行训练,分别的到训练集和测试集的得分
  • 查看模型的参数,并更改参数值,观察模型变化
提示
  • 逻辑回归不是回归模型而是分类模型,不要与LinearRegression混淆
  • 随机森林其实是决策树集成为了降低决策树过拟合的情况
  • 线性模型所在的模块为sklearn.linear_model
  • 树模型所在的模块为sklearn.ensemble
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
# 默认参数逻辑回归模型
lr = LogisticRegression()
lr.fit(X_train, y_train)
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(





LogisticRegression()
# 查看训练集和测试集score值
print('Training set score:{:.2f}'.format(lr.score(X_train, y_train)))
print('Testing set score:{:.2f}'.format(lr.score(X_test, y_test)))
Training set score:0.81
Testing set score:0.78
# C正则化强度的倒数,C越小,损失函数会越小,模型对损失函数的惩罚越重,正则化的效力越强,参数会逐渐被压缩得越来越小。
# 调整参数后的逻辑回归模型
lr2 = LogisticRegression(C=100)
lr2.fit(X_train, y_train)
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(





LogisticRegression(C=100)
# 查看训练集和测试集score值
print('Training set score:{:.2f}'.format(lr2.score(X_train, y_train)))
print('Testing set score:{:.2f}'.format(lr2.score(X_test, y_test)))
Training set score:0.81
Testing set score:0.77

随机森林

# 默认参数的随机森林分类模型
rfc = RandomForestClassifier()
rfc.fit(X_train, y_train)
RandomForestClassifier()
# 查看训练集和测试集score值
print('Training set score:{:.2f}'.format(rfc.score(X_train, y_train)))
print('Testing set score:{:.2f}'.format(rfc.score(X_test, y_test)))
Training set score:1.00
Testing set score:0.82
# 调整参数后的随机森林分类模型
# 调整参数后的随机森林分类模型
# n_estimators:最多的决策树数目,max_depth:最深子树的深度
rfc2 = RandomForestClassifier(n_estimators=100, max_depth=5)
rfc2.fit(X_train, y_train)
RandomForestClassifier(max_depth=5)
print("Training set score: {:.2f}".format(rfc2.score(X_train, y_train)))
print("Testing set score: {:.2f}".format(rfc2.score(X_test, y_test)))
Training set score: 0.86
Testing set score: 0.80

【思考】

  • 为什么线性模型可以进行分类任务,背后是怎么的数学关系

  • 对于多分类问题,线性模型是怎么进行分类的

  • https://blog.csdn.net/m0_37895939/article/details/80506731

  • 1.要使用线性回归来执行分类任务,只需考虑寻找一个联系函数,即将分类标记与线性回归得出的预测值联系起来,即将预测值离散化。这里选取的logistic函数为sigmoid函数。预测值大于0.5,则预测标记为1;预测值小于0.5,则预测标记为0,这样可实现二分类。

import matplotlib.pyplot as plt
import numpy as np
 
def sigmoid(x):
    # 直接返回sigmoid函数
    return 1. / (1. + np.exp(-x))
 
 
def plot_sigmoid():
    # param:起点,终点,间距
    x = np.arange(-8, 8, 0.2)
    y = sigmoid(x)
    plt.plot(x, y)
    plt.show()
 

if __name__ == '__main__':
    plot_sigmoid()

在这里插入图片描述

  • 2.针对多分类问题,可以化解为多个二分类问题,即对每个类别做一次逻辑回归,得到属于该类别的概率,然后在n个类别中选择概率最大的那个类别来作为最后的结果。
任务三:输出模型预测结果
  • 输出模型预测分类标签
  • 输出不同分类标签的预测概率
提示3
  • 一般监督模型在sklearn里面有个predict能输出预测标签,predict_proba则可以输出标签概率
# 预测标签
pred = lr.predict(X_train)
# 看前十位样本的预测标签
pred[:10]
array([0, 0, 1, 0, 1, 1, 1, 0, 0, 1], dtype=int64)
# 预测标签概率
pred_proba = lr.predict_proba(X_train)
# 看前十位样本的标签概率
pred_proba[:10]
# 前面概率是0的,后面概率是1的
array([[0.5553049 , 0.4446951 ],
       [0.89596125, 0.10403875],
       [0.06194643, 0.93805357],
       [0.91132617, 0.08867383],
       [0.10301752, 0.89698248],
       [0.09874944, 0.90125056],
       [0.22245931, 0.77754069],
       [0.90955404, 0.09044596],
       [0.87933886, 0.12066114],
       [0.06972934, 0.93027066]])

【思考】

  • 预测标签的概率对我们有什么帮助

#思考回答

  • 答:观察预测标签的概率,进行分类的阈值调整,这样可以进一步提高预测标签准确率。

第三章 模型搭建和评估-评估

根据之前的模型的建模,我们知道如何运用sklearn这个库来完成建模,以及我们知道了的数据集的划分等等操作。那么一个模型我们怎么知道它好不好用呢?以至于我们能不能放心的使用模型给我的结果呢?那么今天的学习的评估,就会很有帮助。

加载下面的库

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from IPython.display import Image
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.figsize'] = (10, 6)  # 设置输出图片大小

任务:加载数据并分割测试集和训练集

from sklearn.model_selection import train_test_split
# 读取特征clear和标签'Survived'
train = pd.read_csv('train.csv')
clear = pd.read_csv('clear_data.csv')
X = clear
y = train['Survived']
# 对数据集进行分割
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=47)
# 查看数据形状
X_train.shape, X_test.shape
((668, 11), (223, 11))
y_train.shape, y_test.shape
((668,), (223,))

模型评估

  • 模型评估是为了知道模型的泛化能力。
  • 交叉验证(cross-validation)是一种评估泛化性能的统计学方法,它比单次划分训练集和测试集的方法更加稳定、全面。
  • 在交叉验证中,数据被多次划分,并且需要训练多个模型。
  • 最常用的交叉验证是 k 折交叉验证(k-fold cross-validation),其中 k 是由用户指定的数字,通常取 5 或 10。
  • 准确率(precision)度量的是被预测为正例的样本中有多少是真正的正例
  • 召回率(recall)度量的是正类样本中有多少被预测为正类
  • f-分数是准确率与召回率的调和平均

【思考】:将上面的概念进一步的理解,大家可以做一下总结

#思考回答:

  • 1.模型评估即评估模型在测试集上的识别效果,。训练好的模型用一组新的样本来评估模型,模型的表现能力不足,则说明模型泛化能力不够,叫做过拟合。
  • 2.交叉验证是通过将训练集平均分为n分其中的一份作为验证集,验证集是在每训练一轮模型后对模型进行评估,通过交叉验证的验证集是交替变换的。
  • 3.准确率:指的是你预测的10个正的样品中,它真正标签为正的数量为9,准确率为0.9。
  • 4.召回率:指的是你预测了10个正的样品,它真正标签为正的数量(9)占所有标签为正的数量(15=9+6)之比为9/15。
  • 5.F−score=(1+β^2)∗ (精确率∗召回率)/(β^2∗精确率+召回率))
任务一:交叉验证
  • 用10折交叉验证来评估之前的逻辑回归模型
  • 计算交叉验证精度的平均值
#提示:交叉验证
Image('Snipaste_2020-01-05_16-37-56.png')

在这里插入图片描述

提示4
  • 交叉验证在sklearn中的模块为sklearn.model_selection
# 加载库
from sklearn.model_selection import cross_val_score
lr = LogisticRegression(C=100)
# 准确性  默认是scoring='accuracy'
scores = cross_val_score(lr, X_train, y_train, cv=10, scoring='accuracy')
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
# k折交叉验证分数 
scores
array([0.85074627, 0.80597015, 0.7761194 , 0.74626866, 0.82089552,
       0.80597015, 0.74626866, 0.79104478, 0.84848485, 0.81818182])
# 平均交叉验证准确性分数
print("Average cross_validation score: {:.2f}".format(scores.mean()))
Average cross_validation score: 0.80
思考4
  • k折越多的情况下会带来什么样的影响?

答:k折越多,平均误差被视为泛化误差这个结果就越可靠,但相应的所花费的时间也是线性增长的。

任务二:混淆矩阵
  • 计算二分类问题的混淆矩阵
  • 计算精确率、召回率以及f-分数

【思考】什么是二分类问题的混淆矩阵,理解这个概念,知道它主要是运算到什么任务中的

答:混淆矩阵就是分别统计分类模型归错类,归对类的观测值个数,然后把结果放在一个表里展示出来,主要有四个值组成:TN、FP、FN、TP。混淆矩阵多用于判断分类器(Classifier)的优劣,适用于分类型的数据模型,如分类树(Classification Tree)、逻辑回归(Logistic Regression)、线性判别分析(Linear Discriminant Analysis)等方法。

#提示:混淆矩阵
Image('Snipaste_2020-01-05_16-38-26.png')

在这里插入图片描述

#提示:准确率 (Accuracy),精确度(Precision),Recall,f-分数计算方法
Image('Snipaste_2020-01-05_16-39-27.png')

在这里插入图片描述

提示5
  • 混淆矩阵的方法在sklearn中的sklearn.metrics模块
  • 混淆矩阵需要输入真实标签和预测标签
  • 精确率、召回率以及f-分数可使用classification_report模块
from sklearn.metrics import confusion_matrix,classification_report
# 搭建和训练模型
lr = LogisticRegression(C=100)
lr.fit(X_train, y_train)
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(





LogisticRegression(C=100)
pred = lr.predict(X_train)
confusion_matrix(y_train, pred)
array([[363,  49],
       [ 81, 175]], dtype=int64)
print(classification_report(y_train, pred))
              precision    recall  f1-score   support

           0       0.82      0.88      0.85       412
           1       0.78      0.68      0.73       256

    accuracy                           0.81       668
   macro avg       0.80      0.78      0.79       668
weighted avg       0.80      0.81      0.80       668

【思考】

  • 如果自己实现混淆矩阵的时候该注意什么问题

答:自己实现混淆矩阵时要注意分清楚哪些是TP、TN、FP、FN,这样才能对应好矩阵的数值。

任务三:ROC曲线
  • 绘制ROC曲线

【思考】什么是ROC曲线,ROC曲线的存在是为了解决什么问题?

# https://blog.csdn.net/zdy0_2004/article/details/44948511?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase
# https://blog.csdn.net/qq_30992103/article/details/99730059?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162687455916780262579579%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=162687455916780262579579&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-1-99730059.first_rank_v2_pc_rank_v29&utm_term=ROC%E6%9B%B2%E7%BA%BF%E4%BD%BF%E7%94%A8%E5%8E%9F%E5%9B%A0&spm=1018.2226.3001.4187
  • roc曲线:接收者操作特征(receiveroperating characteristic),roc曲线上每个点反映着对同一信号刺激的感受性。

  • 使用的原因:对应于同一个模型,当其中的正负样本分布发生变化时,ROC曲线能够基本保持不变,这就保证至少在模型评估阶段,样本分布不会对这一过程产生太大的影响。

  • 1.(1)真正类率(True Postive Rate)TPR: TP/(TP+FN),代表分类器预测的正类中实际正实例占所有正实例的比例。Sensitivity

  • (2)负正类率(False Postive Rate)FPR: FP/(FP+TN),代表分类器预测的正类中实际负实例占所有负实例的比例。1-Specificity

  • (3)真负类率(True Negative Rate)TNR: TN/(FP+TN),代表分类器预测的负类中实际负实例占所有负实例的比例,TNR=1-FPR。Specificity

  • 假设采用逻辑回归分类器,其给出针对每个实例为正类的概率,那么通过设定一个阈值如0.6,概率大于等于0.6的为正类,小于0.6的为负类。对应的就可以算出一组(FPR,TPR),在平面中得到对应坐标点。随着阈值的逐渐减小,越来越多的实例被划分为正类,但是这些正类中同样也掺杂着真正的负实例,即TPR和FPR会同时增大。阈值最大时,对应坐标点为(0,0),阈值最小时,对应坐标点(1,1)。

  • 理想目标:TPR=1,FPR=0,即图中(0,1)点,故ROC曲线越靠拢(0,1)点,越偏离45度对角线越好,Sensitivity、Specificity越大效果越好。

提示6
  • ROC曲线在sklearn中的模块为sklearn.metrics
  • ROC曲线下面所包围的面积越大越好
# https://blog.csdn.net/hesongzefairy/article/details/104302499?ops_request_misc=&request_id=&biz_id=102&utm_term=ROC%E6%9B%B2%E7%BA%BF%E5%9C%A8sklearn%E4%B8%AD%E7%9A%84%E6%A8%A1%E5%9D%97%E4%B8%BAsklearn.metr&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-2-.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
from sklearn.metrics import roc_curve
# 返回值:(tpr,fpr,thershold)
# tpr:根据不同阈值得到一组tpr值。
# fpr:根据不同阈值的到一组fpr值,与tpr一一对应。(这两个值就是绘制ROC曲线的关键)
# thresholds:选择的不同阈值,按照降序排列。
# decision_function就是用来衡量待预测样本到分类模型各个分隔超平面的距离
# 二分类模型中,decision_function返回的数组形状等于样本个数,也就是一个样本返回一个decision_function值
df = lr.decision_function(X_test)
df[:10]
array([ 3.87344031,  1.23406019,  1.53023448,  2.28810922,  2.67330274,
        0.80702044, -1.94856496, -1.550782  , -1.5752215 , -1.9966667 ])
fpr, tpr, thresholds = roc_curve(y_test, df, pos_label=1)
thresholds
array([ 6.71215618,  5.71215618,  2.45567199,  2.42706135,  1.42543992,
        1.37571842,  1.23406019,  1.13595644,  1.08877618,  1.0466142 ,
        0.92601589,  0.88979372,  0.86003572,  0.84905919,  0.84822321,
        0.79572652,  0.79402258,  0.79156127,  0.78116621,  0.77279708,
        0.75606031,  0.71892886,  0.67223113,  0.59668909,  0.58234   ,
        0.54006584,  0.49368688,  0.42280822,  0.41656714,  0.39422787,
        0.36058848, -0.12124953, -0.39960922, -0.51139381, -0.55365317,
       -0.57692536, -0.60514946, -0.65199322, -0.69764175, -0.70563609,
       -0.74503983, -0.79373398, -0.82218121, -1.0192506 , -1.08065724,
       -1.4263368 , -1.44629126, -1.550782  , -1.5752215 , -1.61275256,
       -1.633806  , -1.64536655, -1.65389948, -1.68861409, -1.71941162,
       -1.84263201, -1.86840487, -2.07811649, -2.08756223, -2.10844618,
       -2.12493328, -2.21795767, -2.25095111, -2.35790034, -2.37241068,
       -3.15370888])
plt.plot(fpr, tpr, label='ROC Curve', lw=2)
plt.xlabel("FPR")
plt.ylabel("TPR (recall)")
# 找到最接近于0的阈值的下标
close_zero = np.argmin(np.abs(thresholds))
plt.plot(fpr[close_zero], tpr[close_zero], 'o', markersize=10, label='threshold zero', fillstyle='none')
plt.legend(loc=4)
<matplotlib.legend.Legend at 0x14be14bb130>

在这里插入图片描述

思考6
  • 对于多分类问题如何绘制ROC曲线

答:对于多分类问题,ROC曲线的获取:假设有n个类别,每种类别下,都可以得到m个测试样本为该类别的概率,可以计算出各个阈值下的假正例率(FPR)和真正例率(TPR),从而绘制出一条ROC曲线。这样总共可以绘制出n条ROC曲线。最后对n条ROC曲线取平均,即可得到最终的ROC曲线。

【思考】你能从这条ROC曲线的到什么信息?这些信息可以做什么?

答:1)可以计算ROC曲线下的面积(AUC),AUC的面积越大说明模型的分类能力越强。 2)选择最佳的诊断界限值。ROC曲线越靠近左上角,试验的准确性就越高。最靠近左上角的ROC曲线的点是错误最少的最好阈值,其假阳性和假阴性的总数最少。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值