↑↑↑关注后"星标"Datawhale

每日干货 & 每月组队学习,不错过

Datawhale干货

作者:李祖贤  深圳大学,Datawhale高校群成员

机器学习分为两类基本问题----回归与分类。在之前的文章中,也介绍了很多基本的机器学习模型。可在Datawhale机器学习专辑中查看。

但是,当我们建立好了相关模型以后我们怎么评价我们建立的模型的好坏以及优化我们建立的模型呢?那本次分享的内容就是关于机器学习模型评估与超参数调优的。本次分享的内容包括:

  • 用管道简化工作流

  • 使用k折交叉验证评估模型性能

  • 使用学习和验证曲线调试算法

  • 通过网格搜索进行超参数调优

  • 比较不同的性能评估指标

一、用管道简化工作流

在很多机器学习算法中,我们可能需要做一系列的基本操作后才能进行建模,如:在建立逻辑回归之前,我们可能需要先对数据进行标准化,然后使用PCA将维,最后拟合逻辑回归模型并预测。那有没有什么办法可以同时进行这些操作,使得这些操作形成一个工作流呢?下面请看代码:

1. 加载基本工具库

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use("ggplot")
import warnings
warnings.filterwarnings("ignore")

2. 加载数据,并做基本预处理

# 加载数据
df = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data",header=None)
# 做基本的数据预处理
from sklearn.preprocessing import LabelEncoderX = df.iloc[:,2:].values
y = df.iloc[:,1].values
le = LabelEncoder()    #将M-B等字符串编码成计算机能识别的0-1
y = le.fit_transform(y)
le.transform(['M','B'])
# 数据切分8:2
from sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,stratify=y,random_state=1)

3. 把所有的操作全部封在一个管道pipeline内形成一个工作流:标准化+PCA+逻辑回归

完成以上操作,共有两种方式:

方式1:make_pipeline

# 把所有的操作全部封在一个管道pipeline内形成一个工作流:
## 标准化+PCA+逻辑回归### 方式1:make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipelinepipe_lr1 = make_pipeline(StandardScaler(),PCA(n_components=2),LogisticRegression(random_state=1))
pipe_lr1.fit(X_train,y_train)
y_pred1 = pipe_lr.predict(X_test)
print("Test Accuracy: %.3f"% pipe_lr1.score(X_test,y_test))
Test Accuracy: 0.956

方式2:Pipeline

# 把所有的操作全部封在一个管道pipeline内形成一个工作流:
## 标准化+PCA+逻辑回归### 方式2:Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipelinepipe_lr2 = Pipeline([['std',StandardScaler()],['pca',PCA(n_components=2)],['lr',LogisticRegression(random_state=1)]])
pipe_lr2.fit(X_train,y_train)
y_pred2 = pipe_lr2.predict(X_test)
print("Test Accuracy: %.3f"% pipe_lr2.score(X_test,y_test))
Test Accuracy: 0.956

二、使用k折交叉验证评估模型性能

评估方式1:k折交叉验证

# 评估方式1:k折交叉验证from sklearn.model_selection import cross_val_scorescores1 = cross_val_score(estimator=pipe_lr,X = X_train,y = y_train,cv=10,n_jobs=1)
print("CV accuracy scores:%s" % scores1)
print("CV accuracy:%.3f +/-%.3f"%(np.mean(scores1),np.std(scores1)))

评估方式2:分层k折交叉验证

# 评估方式2:分层k折交叉验证from sklearn.model_selection import StratifiedKFoldkfold = StratifiedKFold(n_splits=10,random_state=1).split(X_train,y_train)
scores2 = []
for k,(train,test) in enumerate(kfold):pipe_lr.fit(X_train[train],y_train[train])score = pipe_lr.score(X_train[test],y_train[test])scores2.append(score)print('Fold:%2d,Class dist.:%s,Acc:%.3f'%(k+1,np.bincount(y_train[train]),score))
print('\nCV accuracy :%.3f +/-%.3f'%(np.mean(scores2),np.std(scores2)))

三、 使用学习和验证曲线调试算法

如果模型过于复杂,即模型有太多的自由度或者参数,就会有过拟合的风险(高方差);而模型过于简单,则会有欠拟合的风险(高偏差)。

下面我们用这些曲线去识别并解决方差和偏差问题:

1. 用学习曲线诊断偏差与方差

# 用学习曲线诊断偏差与方差
from sklearn.model_selection import learning_curvepipe_lr3 = make_pipeline(StandardScaler(),LogisticRegression(random_state=1,penalty='l2'))
train_sizes,train_scores,test_scores = learning_curve(estimator=pipe_lr3,X=X_train,y=y_train,train_sizes=np.linspace(0.1,1,10),cv=10,n_jobs=1)
train_mean = np.mean(train_scores,axis=1)
train_std = np.std(train_scores,axis=1)
test_mean = np.mean(test_scores,axis=1)
test_std = np.std(test_scores,axis=1)
plt.plot(train_sizes,train_mean,color='blue',marker='o',markersize=5,label='training accuracy')
plt.fill_between(train_sizes,train_mean+train_std,train_mean-train_std,alpha=0.15,color='blue')
plt.plot(train_sizes,test_mean,color='red',marker='s',markersize=5,label='validation accuracy')
plt.fill_between(train_sizes,test_mean+test_std,test_mean-test_std,alpha=0.15,color='red')
plt.xlabel("Number of training samples")
plt.ylabel("Accuracy")
plt.legend(loc='lower right')
plt.ylim([0.8,1.02])
plt.show()

2. 用验证曲线解决欠拟合和过拟合

# 用验证曲线解决欠拟合和过拟合
from sklearn.model_selection import validation_curvepipe_lr3 = make_pipeline(StandardScaler(),LogisticRegression(random_state=1,penalty='l2'))
param_range = [0.001,0.01,0.1,1.0,10.0,100.0]
train_scores,test_scores = validation_curve(estimator=pipe_lr3,X=X_train,y=y_train,param_name='logisticregression__C',param_range=param_range,cv=10,n_jobs=1)
train_mean = np.mean(train_scores,axis=1)
train_std = np.std(train_scores,axis=1)
test_mean = np.mean(test_scores,axis=1)
test_std = np.std(test_scores,axis=1)
plt.plot(param_range,train_mean,color='blue',marker='o',markersize=5,label='training accuracy')
plt.fill_between(param_range,train_mean+train_std,train_mean-train_std,alpha=0.15,color='blue')
plt.plot(param_range,test_mean,color='red',marker='s',markersize=5,label='validation accuracy')
plt.fill_between(param_range,test_mean+test_std,test_mean-test_std,alpha=0.15,color='red')
plt.xscale('log')
plt.xlabel("Parameter C")
plt.ylabel("Accuracy")
plt.legend(loc='lower right')
plt.ylim([0.8,1.02])
plt.show()

四、通过网格搜索进行超参数调优

如果只有一个参数需要调整,那么用验证曲线手动调整是一个好方法,但是随着需要调整的超参数越来越多的时候,我们能不能自动去调整呢?!!!注意对比各个算法的时间复杂度。

(注意参数与超参数的区别:参数可以通过优化算法进行优化,如逻辑回归的系数;超参数是不能用优化模型进行优化的,如正则话的系数。)

方式1:网格搜索GridSearchCV()

# 方式1:网格搜索GridSearchCV()
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
import timestart_time = time.time()
pipe_svc = make_pipeline(StandardScaler(),SVC(random_state=1))
param_range = [0.0001,0.001,0.01,0.1,1.0,10.0,100.0,1000.0]
param_grid = [{'svc__C':param_range,'svc__kernel':['linear']},{'svc__C':param_range,'svc__gamma':param_range,'svc__kernel':['rbf']}]
gs = GridSearchCV(estimator=pipe_svc,param_grid=param_grid,scoring='accuracy',cv=10,n_jobs=-1)
gs = gs.fit(X_train,y_train)
end_time = time.time()
print("网格搜索经历时间:%.3f S" % float(end_time-start_time))
print(gs.best_score_)
print(gs.best_params_)

方式2:随机网格搜索RandomizedSearchCV()

# 方式2:随机网格搜索RandomizedSearchCV()
from sklearn.model_selection import RandomizedSearchCV
from sklearn.svm import SVC
import timestart_time = time.time()
pipe_svc = make_pipeline(StandardScaler(),SVC(random_state=1))
param_range = [0.0001,0.001,0.01,0.1,1.0,10.0,100.0,1000.0]
param_grid = [{'svc__C':param_range,'svc__kernel':['linear']},{'svc__C':param_range,'svc__gamma':param_range,'svc__kernel':['rbf']}]
# param_grid = [{'svc__C':param_range,'svc__kernel':['linear','rbf'],'svc__gamma':param_range}]
gs = RandomizedSearchCV(estimator=pipe_svc, param_distributions=param_grid,scoring='accuracy',cv=10,n_jobs=-1)
gs = gs.fit(X_train,y_train)
end_time = time.time()
print("随机网格搜索经历时间:%.3f S" % float(end_time-start_time))
print(gs.best_score_)
print(gs.best_params_)

方式3:嵌套交叉验证

# 方式3:嵌套交叉验证
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
import timestart_time = time.time()
pipe_svc = make_pipeline(StandardScaler(),SVC(random_state=1))
param_range = [0.0001,0.001,0.01,0.1,1.0,10.0,100.0,1000.0]
param_grid = [{'svc__C':param_range,'svc__kernel':['linear']},{'svc__C':param_range,'svc__gamma':param_range,'svc__kernel':['rbf']}]
gs = GridSearchCV(estimator=pipe_svc, param_grid=param_grid,scoring='accuracy',cv=2,n_jobs=-1)
scores = cross_val_score(gs,X_train,y_train,scoring='accuracy',cv=5)
end_time = time.time()
print("嵌套交叉验证:%.3f S" % float(end_time-start_time))
print('CV accuracy :%.3f +/-%.3f'%(np.mean(scores),np.std(scores)))

五、比较不同的性能评估指标

有时候,准确率不是我们唯一需要考虑的评价指标,因为有时候会存在各类预测错误的代价不一样。例如:在预测一个人的肿瘤疾病的时候,如果病人A真实得肿瘤但是我们预测他是没有肿瘤,跟A真实是健康但是预测他是肿瘤,二者付出的代价很大区别(想想为什么)。所以我们需要其他更加广泛的指标:

1. 绘制混淆矩阵

# 绘制混淆矩阵
from sklearn.metrics import confusion_matrixpipe_svc.fit(X_train,y_train)
y_pred = pipe_svc.predict(X_test)
confmat = confusion_matrix(y_true=y_test,y_pred=y_pred)
fig,ax = plt.subplots(figsize=(2.5,2.5))
ax.matshow(confmat, cmap=plt.cm.Blues,alpha=0.3)
for i in range(confmat.shape[0]):for j in range(confmat.shape[1]):ax.text(x=j,y=i,s=confmat[i,j],va='center',ha='center')
plt.xlabel('predicted label')
plt.ylabel('true label')
plt.show()

2. 各种指标的计算

# 各种指标的计算
from sklearn.metrics import precision_score,recall_score,f1_scoreprint('Precision:%.3f'%precision_score(y_true=y_test,y_pred=y_pred))
print('recall_score:%.3f'%recall_score(y_true=y_test,y_pred=y_pred))
print('f1_score:%.3f'%f1_score(y_true=y_test,y_pred=y_pred))

3. 将不同的指标与GridSearch结合

# 将不同的指标与GridSearch结合
from sklearn.metrics import make_scorer,f1_score
scorer = make_scorer(f1_score,pos_label=0)
gs = GridSearchCV(estimator=pipe_svc,param_grid=param_grid,scoring=scorer,cv=10)
gs = gs.fit(X_train,y_train)
print(gs.best_score_)
print(gs.best_params_)

4. 绘制ROC曲线

# 绘制ROC曲线
from sklearn.metrics import roc_curve,auc
from sklearn.metrics import make_scorer,f1_score
scorer = make_scorer(f1_score,pos_label=0)
gs = GridSearchCV(estimator=pipe_svc,param_grid=param_grid,scoring=scorer,cv=10)
y_pred = gs.fit(X_train,y_train).decision_function(X_test)
#y_pred = gs.predict(X_test)
fpr,tpr,threshold = roc_curve(y_test, y_pred) ###计算真阳率和假阳率
roc_auc = auc(fpr,tpr) ###计算auc的值
plt.figure()
lw = 2
plt.figure(figsize=(7,5))
plt.plot(fpr, tpr, color='darkorange',lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) ###假阳率为横坐标,真阳率为纵坐标做曲线
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([-0.05, 1.0])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic ')
plt.legend(loc="lower right")
plt.show()


http://www.taodudu.cc/news/show-123876.html

相关文章:

  • 机器学习数学基础:常见分布与假设检验
  • 基于OpenCV的图像分割处理!
  • NLP入门必知必会(一):Word Vectors
  • 基于OpenCV的图像梯度与边缘检测!
  • 如何用Pandas处理文本数据?
  • 一文总结词向量的计算、评估与优化
  • 项目实践|如何在较暗环境进行人脸检测?
  • 过来人的肺腑之言,攻读ML和CV硕士给我带来了什么?
  • 学习用Pandas处理分类数据!
  • 11/1787, 哈工大小学妹的比赛上分经验,附战友招募
  • Pandas处理时序数据(初学者必会)!
  • 记录理解程度、一篇至少读3遍,吴恩达建议这样读论文!
  • 基于Adaboost算法的人脸检测分类器!
  • 鱼佬阿水竞赛相声:我是如何2小时杀进排名前10%的!
  • SVM算法在项目实践中的应用!
  • 七月组队学习!
  • Tensorflow基础入门十大操作总结
  • kaggle、TDS、arXiv等,我最喜欢的数据科学资源
  • NLP入门 | 通俗讲解Subword Models
  • 深度学习环境配置指南!(Windows、Mac、Ubuntu全讲解)
  • 又一数据挖掘赛事,在校生专属,翼支付杯来了(直通实习机会)
  • ​【特征工程】时序特征挖掘的奇技淫巧
  • 深度学习之Pytorch基础教程!
  • 更新!带你认识推荐系统全貌的论文清单
  • 开源教程 「nlp-tutorial」!用百行代码搞定各类NLP模型
  • 数据维度爆炸怎么办?详解5大常用的特征选择方法
  • 王敏捷 - 深度学习框架这十年!
  • 【特征提取+分类模型】4种常见的NLP实践思路
  • 数据分析(EDA)学习总结!
  • 中科院计算所实习-深度学习方向

机器学习模型评估与超参数调优详解相关推荐

  1. 笔记 | 百度飞浆AI达人创造营:深度学习模型训练和关键参数调优详解

    笔记 | 百度飞浆AI达人创造营:深度学习模型训练和关键参数调优详解 针对特定场景任务从模型选择.模型训练.超参优化.效果展示这四个方面进行模型开发. 一.模型选择 从任务类型出发,选择最合适的模型. ...

  2. 深度学习模型训练和关键参数调优详解

    深度学习模型训练和关键参数调优详解 一.模型选择 1.回归任务 人脸关键点检测 2.分类任务 图像分类 3.场景任务 目标检测 人像分割 文字识别 二.模型训练 1.基于高层API训练模型 加载数据集 ...

  3. Datawhale 集成学习 Task06:掌握分类问题的评估及超参数调优

    超参数调优,主要有GridSearchCV和RandomizedSearchCV,主要是因为上一个task代码少,我就和之前的写在一起了.回忆一下,Grid和Randomized共用了param_ra ...

  4. php+php-fom+nginx配置参数调优详解

    文章目录 一.前言 1.mysql配置参数: 2.注意 二.php参数配置及讲解 1.phpini的基本设置 2.php参数设置 三.php-fpm设置 1.设置子进程数,增加并发量 2.防止频繁出现 ...

  5. k-means聚类算法原理与参数调优详解

    https://www.toutiao.com/a6690435044869145101/ k-means算法原理 K-means中心思想:事先确定常数K,常数K意味着最终的聚类类别数,首先随机选定初 ...

  6. 机器学习——超参数调优

    超参数是在开始学习过程之前设置值的参数,而不是通过训练得到的参数数据.超参数可以分为两种类型:定义模型及结构本身的参数,目标函数与与优化算法所需的参数,前者用于训练和预测阶段,后者用于训练阶段. 在实 ...

  7. 【进阶版】机器学习之特征降维、超参数调优及检验方法(04)

    目录 欢迎订阅本专栏,持续更新中~ 本专栏前期文章介绍! 机器学习配套资源推送 进阶版机器学习文章更新~ 点击下方下载高清版学习知识图册 线性判别分析(LDA) 主成分分析(PCA) 超参数调优 检验 ...

  8. tf.saved_model.save模型导出、TensorFlow Serving模型部署、TensorBoard中的HParams 超参数调优

    日萌社 人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新) 4.11 综合案例:模型导出与部署 学习目标 目标 掌握Ten ...

  9. DL之模型调参:深度学习算法模型优化参数之对LSTM算法进行超参数调优

    DL之模型调参:深度学习算法模型优化参数之对LSTM算法进行超参数调优 目录 基于keras对LSTM算法进行超参数调优 1.可视化LSTM模型的loss和acc曲线

最新文章

  1. mlc tlc slc qlc_看了这么多固态硬盘科普,终于真正搞明白TLC闪存和SLC缓存
  2. 分布式系统 一致性模型的介绍 以及 zookeeper的 “线性一致性“ 讨论
  3. XEN的clone和copy那点事
  4. oracle 峰度 函数,Oracle Database 21c 十大新特性一览
  5. 4位并行加载寄存器设计
  6. Swift基础语法: 30 - Swift的基类, 子类, 重写, 重写方法, 重写属性, 防止重写
  7. html页面内分栏显示不全,怎么消除Word文档分栏后栏间不平衡现象
  8. 51单片机redefinition_lcd12864程序在keil中出现好多重新定义,尝试了很多办法都改不了,求助大家了...
  9. python根据文件名列表筛选满足条件的文件
  10. 【笔记】Altera - Quartus II使用方法——工程创建、Modelsim破解/仿真、Verilog编写、举例(待续)
  11. 前端汉字encode_js编码转码中文
  12. 2021年危险化学品经营单位安全管理人员考试及危险化学品经营单位安全管理人员作业考试题库
  13. 易观分析联合中小银行联盟发布海南数字经济指数,敬请期待!
  14. linux波浪线是什么路径,波浪线符号(linux运维中特殊符号)
  15. 我市“一卡通”被授予国家金卡工程优秀应用成果奖
  16. 3D打印技术如何影响未来
  17. 中小企业 数量 e-mail_【深圳】市中小企业服务局关于发布2021年深圳市工业设计发展扶持计划工业设计走进中小微制造企业扶持项目申请指南的通知...
  18. Visual Paradigm下载并设置中文
  19. 本科学位计算机要考吗,本科毕业需要考计算机二级吗
  20. XP系统无法设置用户权限,如加everyone等的

热门文章

  1. 1、IO输入输出流 简介
  2. unity中摄像机的控制---调整摄像机,不让他摔倒
  3. 测试思想 什么是软件测试(摘录)
  4. 读大叔深入理解javascript(2)
  5. 【组队学习】【32期】数据可视化(Matplotlib)
  6. 【青少年编程竞赛交流】11月份微信图文索引
  7. 如何利用Seaborn绘制热力图?
  8. LeetCode实战:合并两个有序数组
  9. LeetCode实战:最长回文子串
  10. LeetCode实战:逆波兰表达式求值