当前位置:网站首页>7_数据分析—评估
7_数据分析—评估
2022-04-21 09:47:00 【IT-cute】
一、前期准备
# %matplotlib inline这一句是IPython的魔法函数,可以在IPython编译器里直接使用,作用是内嵌画图,省略掉plt.show()这一步,直接显示图像。
#如果不加这一句的话,我们在画图结束之后需要加上plt.show()才可以显示图像。
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import Image
from sklearn.model_selection import train_test_split
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.figsize'] = (10, 6) # 设置输出图片大小
1.1 加载数据并分割数据集
from sklearn.model_selection import train_test_split
# 一般先取出X和y后再切割,有些情况会使用到未切割的,这时候X和y就可以用,x是清洗好的数据,y是我们要预测的存活数据'Survived'
data = pd.read_csv('clear_data.csv')
train = pd.read_csv('train.csv')
X = data
y = train['Survived']
# 对数据集进行切割
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
# 默认参数逻辑回归模型
lr = LogisticRegression()
lr.fit(X_train, y_train)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='auto', n_jobs=None, penalty='l2', random_state=None, solver='lbfgs', tol=0.0001, verbose=0, warm_start=False)
二、模型评估
- 模型评估是为了知道模型的泛化能力。
- 交叉验证(cross-validation)是一种评估泛化性能的统计学方法,它比单次划分训练集和测试集的方法更加稳定、全面。
- 在交叉验证中,数据被多次划分,并且需要训练多个模型。
- 最常用的交叉验证是 k 折交叉验证(k-fold cross-validation),其中 k 是由用户指定的数字,通常取 5 或 10。
- 准确率(precision)度量的是被预测为正例的样本中有多少是真正的正例
- 召回率(recall)度量的是正类样本中有多少被预测为正类
- f-分数是准确率与召回率的调和平均
2.1 交叉验证
- 用10折交叉验证来评估之前的逻辑回归模型
- 计算交叉验证精度的平均值
#提示:交叉验证
Image('Snipaste_2020-01-05_16-37-56.png')
# i=Image.open('Snipaste_2020-01-05_16-37-56.png')
# plt.figure("dd")
# plt.imshow(i)
# plt.show()

提示:
- 交叉验证在sklearn中的模块为
sklearn.model_selection
from sklearn.model_selection import cross_val_score
lr = LogisticRegression(C=100)
# k折交叉验证分数
scores = cross_val_score(lr, X_train, y_train, cv=10)
print(scores)
""" array([0.85074627, 0.74626866, 0.74626866, 0.80597015, 0.88059701, 0.8358209 , 0.76119403, 0.8358209 , 0.74242424, 0.75757576]) """
# 平均交叉验证分数
print("Average cross-validation score: {:.2f}".format(scores.mean()))
# Average cross-validation score: 0.80
思考:k折越多的情况下会带来什么样的影响?
答:K折越多,单次训练验证时,用作训练集的数据就会越多,而用作验证集的数据越少。这样平均的结果会更加可靠,但是所耗费的总时间也会增多。(用大量数据换取结果的可靠,时间增加。)
2.2 混淆矩阵
- 计算二分类问题的混淆矩阵
- 计算精确率、召回率以及f-分数
混淆矩阵:又称为可能性表格或是错误矩阵。它是一种特定的矩阵用来呈现算法性能的可视化效果,通常是监督学习(非监督学习,通常用匹配矩阵:matching matrix)。其每一列代表预测值,每一行代表的是实际的类别。这个名字来源于它可以非常容易的表明多个类别是否有混淆(也就是一个class被预测成另一个class)。

提示:
- 混淆矩阵的方法在sklearn中的
sklearn.metrics模块 - 混淆矩阵需要输入真实标签和预测标签
- 精确率、召回率以及f-分数可使用
classification_report模块
from sklearn.metrics import confusion_matrix
# 训练模型
lr = LogisticRegression(C=100)
lr.fit(X_train, y_train)
# 模型预测结果
pred = lr.predict(X_train)
# 混淆矩阵
confusion_matrix(y_train, pred)
""" array([[354, 58], [ 83, 173]]) """
from sklearn.metrics import classification_report
# 精确率、召回率以及f1-score
print(classification_report(y_train, pred))
precision recall f1-score support 0 0.81 0.86 0.83 412 1 0.75 0.68 0.71 256 accuracy 0.79 668 macro avg 0.78 0.77 0.77 668 weighted avg 0.79 0.79 0.79 668
2.3 ROC曲线
提示:
- ROC曲线在sklearn中的模块为
sklearn.metrics - ROC曲线下面所包围的面积越大越好
from sklearn.metrics import roc_curve
# ROC曲线下面所包围的面积越大越好
fpr, tpr, thresholds = roc_curve(y_test, lr.decision_function(X_test))
plt.plot(fpr, tpr, label="ROC Curve")
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", c='k', mew=2)
plt.legend(loc=4)
plt.show()
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZVVK9uA4-1650461280881)(https://gitee.com/IT-cute/Picbed/raw/master/img/下载 (2)].png)](/img/62/8fc919ce07e059b3c8a93e72fdd50a.png)
版权声明
本文为[IT-cute]所创,转载请带上原文链接,感谢
https://blog.csdn.net/brawly/article/details/124307911
边栏推荐
- [note] package XML file syntax record
- 【手拉手 带你准备电赛】单色块识别(基于openmv)
- Write table of MySQL Foundation (create table)
- 2022 refrigeration and air conditioning equipment operation test question simulation test question bank and answers
- ZABBIX 5.4 server installation
- C语言进阶-动态内存管理
- 【PyCharm Plugins】网上下载,来安装Translation插件
- 【愚公系列】2022年04月 微信小程序-地图的使用之线聚合
- 【手拉手 带你准备电赛】近期小总结
- Daily question (2022-04-20) - the longest absolute path of the file
猜你喜欢

【手拉手 带你准备电赛】April Tag标记跟踪(3D定位)详解
![[hand in hand to prepare you for the video game] monochrome block recognition (based on openmv)](/img/85/34247a2470295bf6a61dcd7c0cafd9.png)
[hand in hand to prepare you for the video game] monochrome block recognition (based on openmv)
![[Excel函数] COUNT函数 | COUNTIF函数 | COUNTIFS函数](/img/fa/440ea44a9fa5a74fe4b8fc172dd493.png)
[Excel函数] COUNT函数 | COUNTIF函数 | COUNTIFS函数

2022年A特种设备相关管理(电梯)考试试题模拟考试平台操作

Fudan University - University of Washington EMBA Alumni: Turning "her power" into "our power"

计算器(力扣)

Grid layout -- grid

风尚云网学习-js实现禁用右键以及F12

2022危险化学品经营单位主要负责人上岗证题库及模拟考试

VR panorama is suitable for those industries
随机推荐
CentOS下Docker中安装redis
VR panorama is suitable for those industries
【每日一题】跳石板--动态规划
控制另一个程序的启动、隐藏、显示、关闭
【无标题】定时的
Promise handles complex asynchrony
Operation of simulation test platform for test questions of refrigeration and air conditioning equipment operation test in 2022
Control the start, hide, display and close of another program
SQL question set [(2)]
Operating system - thread safety - Learning
[Netty ]自己实现一个redis客户端难吗?
Question brushing record (leetcode)
Canoe: what is the vector tool platform
Responsive layout to realize the static page of ghost blog home page
ConvNeXt
比 Navicat 还要好用、功能更强大的工具!
刷题记录(leetcode)
【手拉手 带你准备电赛】April Tag标记跟踪(3D定位)详解
Regular expression syntax and common regular expressions
Install MySQL in docker under CentOS